Finding sum of alternative elements of the array in JavaScript


We are required to write a JavaScript function that takes in an array of Numbers as the only argument. The function should calculate and return the sum of alternative elements of the array.

For example −

If the input array is −

const arr = [1, 2, 3, 4, 5, 6, 7];

Then the output should be −

1 + 3 + 5 + 7 = 16

Example

Following is the code −

const arr = [1, 2, 3, 4, 5, 6, 7];
const alternativeSum = (arr = []) => {
   let sum = 0;
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      if(i % 2 !== 0){
         continue;
      };
      sum += el;
   };
   return sum;
};
console.log(alternativeSum(arr));

Output

Following is the output on console −

16

Updated on: 10-Dec-2020

746 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements