- Related Questions & Answers
- How to find the sum of all the numbers in an array in java?
- How to find the Odd and Even numbers in an Array in java?
- 8085 program to find the sum of series of even numbers
- Sum of squares of the first n even numbers in C Program
- How to pull even numbers from an array in MongoDB?
- Sum of Even Numbers After Queries in Python
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array?
- Add minimum number to an array so that the sum becomes even in C++?
- Add minimum number to an array so that the sum becomes even in C programming
- How do you find the sum of all the numbers in a java array
- Sum of even numbers up to using recursive function in JavaScript
- How to get the first element of an array in PHP?
- How to find the sum of elements of an Array using STL in C++?
- 8086 program to find sum of Even numbers in a given series
- Print prime numbers with prime sum of digits in an array

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

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

9

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.

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

9

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.

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

9

Advertisements