We are required to write a JavaScript function that takes in an array of numbers and returns the alternative multiplicative sum of the elements.
For example: If the array is −
const arr = [1, 2, 3, 4, 5, 6, 7];
Then the output should be calculated like this −
1*2+3*4+5*6+7 2+12+30+7
And the output should be −
51
Let’s write the code for this function −
Example
The code for this will be −
const arr = [1, 2, 3, 4, 5, 6, 7]; const alternateOperation = arr => { const productArr = arr.reduce((acc, val, ind) => { if(ind % 2 === 1){ return acc; }; acc.push(val * (arr[ind + 1] || 1)); return acc; }, []); return productArr.reduce((acc, val) => acc + val); }; console.log(alternateOperation(arr));
Output
The output in the console −
51