Solemn Messiah
Solemn Messiah

Reputation: 121

Summing Array Elements from Specific Index Range

I have tried to look at many things for this but I simply cannot figure out how to make it work. I am very new to coding in general, so it may be a lack of understanding! Simply put, I have a an array with a set amount of elements, and I want to be able to sum up consecutive elements, starting from a specific index and ending at specific index.

const array = [1,2,3,4,5,6]

I want to be able to sum index 1 and 3, which in this case would be 2+4 =6.

Is there a way to use array.filter() or just use a function where I sum based on the array.indexof()?

Upvotes: 8

Views: 15863

Answers (3)

Unmitigated
Unmitigated

Reputation: 89412

If you want to sum all the elements between two indexes, you can use a simple index based for loop.

let start = 1, end = 3, sum = 0;
for(let i = start; i <= end; i++)
     sum += array[i];

slice and reduce can also be used:

let sum = array.slice(start, end+1).reduce((a,b)=>a+b,0);

If you just want the sum of the elements at two specific indexes, you can access the elements using bracket notation.

let sum = array[1]+array[3];

If you have an array of indexes to sum, you can loop over each index like so:

let indexes = [1, 3], sum = 0;
for(let index of indexes){
    sum += array[index];
}

reduce can be used as well.

let indexes = [1, 3];
let sum = indexes.reduce((acc, cur)=>acc+array[cur],0);

Upvotes: 10

Sven.hig
Sven.hig

Reputation: 4519

You could use slice to take a chunk of the array and then use reduce

const array = [1,2,3,4,5,6]
subar = array.slice(1,4)
res = subar.reduce((acc , curr, i) => acc = acc + curr ,0)
console.log(res)

Upvotes: 0

Asutosh
Asutosh

Reputation: 1828

Try

const array = [1,2,3,4,5,6];
var startInd=1;
var endInd=3;
console.log(array[startInd]+array[endInd]);

Upvotes: 0

Related Questions