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()
?
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()
?
- Are you trying to sum all elements in a range or just two specific elements? – Unmitigated Commented Jul 28, 2020 at 5:03
- The sum of all elements from index 1 to 3 is not 6. – Unmitigated Commented Jul 28, 2020 at 5:03
3 Answers
Reset to default 10If 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);
Try
const array = [1,2,3,4,5,6];
var startInd=1;
var endInd=3;
console.log(array[startInd]+array[endInd]);
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)