So I was wondering, if there is a shorter or different way to get the sum of FEW numbers in an array, not the complete array. For example if i want to get the sum of first 3 numbers in array, I know I can go trough loop like this:
var arr=[1,2,3,4,5];
var sum=0;
for(var i=0; i<3;i++){
sum+= arr[i];
}
console.log(sum);
But I would like to know if you can somehow use reduce() method? Or even some other built-in method? I tried reduce like this,few times on my own, but it isn't working:
var arr= [1,2,3,4,5];
arr.reduce(function(total,amount,index){
total+=amount;
if(index===2){
return total;
}
});