How to multiply odd index values JavaScript


We are required to write a function, that takes in an array of Number literals as one and the only argument. The numbers that are situated at even index should be returned as it is. But the numbers situated at the odd index should be returned multiplied by their corresponding indices.

For example −

If the input is:
   [5, 10, 15, 20, 25, 30, 50, 100]
Then the function should return:
   [5, 10, 15, 60, 25, 150, 50, 700]

We will use the Array.prototype.reduce() method to construct the required array and the code for the function will be −

Example

const arr = [5, 10, 15, 20, 25, 30, 50, 100];
const multiplyOdd = (arr) => {
   return arr.reduce((acc, val, ind) => {
      if(ind % 2 === 1){
         val *= ind;
      };
      return acc.concat(val);
   }, []);
};
console.log(multiplyOdd(arr));

Output

The output in the console will be −

[
   5, 10, 15, 60,
   25, 150, 50, 700
]

Updated on: 25-Aug-2020

277 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements