We are required to write a JavaScript function that takes in an array of numbers like this −
const arr = [3, 6, 34, 12, 6, 8, 8, 5, 6, 8];
The function should return the difference between the sum of elements present at the odd index and the sum of elements present at even index
Example
Following is the code −
const arr = [3, 6, 34, 12, 6, 8, 8, 5, 6, 8]; const oddEvenDiff = arr => { let diff = 0; for(let i = 0; i < arr.length; i++){ if(i % 2 === 0){ diff += arr[i]; }else{ diff -= arr[i] }; }; return Math.abs(diff); }; console.log(oddEvenDiff(arr));
Output
This will produce the following output in console −
18