Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()?

like image 388
Solemn Messiah Avatar asked Jun 20 '26 19:06

Solemn Messiah


1 Answers

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);
like image 129
Unmitigated Avatar answered Jun 23 '26 08:06

Unmitigated



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!