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

JavaScript Sum odd indexed and even indexed elements separately and return their absolute difference


We are required to write a JavaScript function that takes in an array of numbers. The function should sum odd indexed and even indexed elements separately and finally should return their absolute difference.

Example

const arr = [4, 6, 3, 1, 5, 8, 9, 3, 4];
const oddEvenDifference = (arr = []) => {
   let oddSum = 0;
   let evenSum = 0;
   for(let i = 0;
   i < arr.length; i++){
      const el = arr[i];
      if(i % 2 === 0){
         evenSum += el;
      }else{
         oddSum += el;
      };
 
    };
   return Math.abs(oddSum - evenSum);
};
console.log(oddEvenDifference(arr));

Output

And the output in the console will be −

7