Computer >> Computer tutorials >  >> Programming >> Javascript

How to get the sum of the numbers in even positions in an array?


There are multiple ways to get the sum of numbers in even positions in an array. Let us look at 3 of these −

Using a for loop

We can directly use a for loop and get the sum.

Example

let arr = [1, 2, 3, 4, 5, 6];
let sum = 0;
for(let i = 0; i < arr.length; i += 2) {
   sum += arr[i];
}
console.log(sum);

Output

9

Using a forEach loop

In this method, instead of iterating explicitly over the array, we can instead use the built in function forEach to iterate. It takes a function that is executed for each element.

Example

let arr = [1, 2, 3, 4, 5, 6];
let sum = 0;
arr.forEach((elem, i) => {
   if(i % 2 === 0) {
      sum += elem;
   }
});
console.log(sum);

Output

9

Using filter and reduce

We can use filter and reduce functions to calculate the sum. First we filter the odd indices using filter then we calculate the sum using reduce.

Example

let arr = [1, 2, 3, 4, 5, 6];
let sum = arr.filter((_, i) => i % 2 === 0).reduce((curr, acc) => acc + curr, 0)
console.log(sum);

Output

9