Javascript - Sum of few numbers in array with reduce() or some other built-in method

5.1k views Asked by At

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;
}
});
3

There are 3 answers

0
Jonas Wilms On
arr
 .slice(0,3) //get the range
 .reduce((a,b) => a + b)//sum up

Or without slice:

arr.reduce((a,b,i) => i < 3 ? a + b : a, 0);
0
Oleksandr  Fedotov On

As an example, if you want to skip element by index 2.

var arr = [1,2,3,4,5];
arr.reduce(function(total,amount,index){
    if(index === 2) {
       return total;
    }
    return total + amount;
});

In your case you forgot to return new total, when the index is not 2.

0
Andy On

A function that takes an array, and two numbers representing the element range. It slices the array, and returns the sum of the numbers in that range using reduce.

let arr= [1,2,3,4,5];

function getRangeSum(arr, from, to) {
  return arr.slice(from, to).reduce((p, c) => {
    return p + c;
  }, 0);
} 

console.log(getRangeSum(arr, 2, 4));