Alternate addition multiplication in an array - JavaScript


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, 4, 1, 2, 3, 4, 3];

then the output should be calculated like this −

1*2+4*1+2*3+4*3
2+4+6+12

And the output should be −

24

Example

Let's write the code for this −

const arr = [1, 2, 4, 1, 2, 3, 4, 3];
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: −

24

Updated on: 15-Sep-2020

185 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements