- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- 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

- 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
- How to pull even numbers from an array in MongoDB?
- Sum of squares of the first n even numbers in C Program
- Count Numbers in Range with difference between Sum of digits at even and odd positions as Prime in C++
- Sum of Even Numbers After Queries in Python
- Add minimum number to an array so that the sum becomes even in C++?
- Taking the absolute sum of Array of Numbers in JavaScript
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array?
- Repeating only even numbers inside an array in JavaScript
- Finding even length numbers from an array in JavaScript
- Sum of all prime numbers in an array - JavaScript
- Add minimum number to an array so that the sum becomes even in C programming
- How to get the numbers which can divide all values in an array - JavaScript

Advertisements