1

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 Answers 3

12
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);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.