Product of all other numbers an array in JavaScript


Let’s say, we have to write a function that takes an array of numbers as argument. We have to return a new array with the products of each number except the index we are currently calculating product for.

For example, if arr had 5 indices and we were creating the value for index 1, the numbers at index 0, 2, 3 and 4 would be multiplied. Similarly, if we were creating the value for index 2, the numbers at index 0, 1, 3 and 4 would be multiplied and so on.

Note − It is guaranteed that all the elements inside the array are non-zero.

We will first reduce the array to its product and then we will loop over the array to find the value for that index, we will simply divide the product by the original value at that index.

The code for doing this will be −

Example

const arr = [12, 10, 8, 6, 5, 2];
const produceArray = (arr) => {
   const product = arr.reduce((acc, val) => acc*val);
   return arr.map(el => {
      return product/el;
   });
};
console.log(produceArray(arr));

Output

The output in the console will be −

[ 4800, 5760, 7200, 9600, 11520, 28800 ]

Updated on: 24-Aug-2020

247 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements