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.

Approach

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.

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

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

How It Works

The function works in two steps:

  • Calculate total product: Use reduce() to multiply all numbers in the array
  • Divide by each element: Use map() to divide the total product by each element to get the product of all other elements

Alternative Approach Without Division

If division is not allowed or you want to handle edge cases, you can use nested loops:

const arr = [12, 10, 8, 6, 5, 2];
const produceArrayAlt = (arr) => {
    return arr.map((_, index) => {
        return arr.reduce((acc, val, i) => {
            return i === index ? acc : acc * val;
        }, 1);
    });
};
console.log(produceArrayAlt(arr));
[ 4800, 5760, 7200, 9600, 11520, 28800 ]

Conclusion

The division approach is more efficient with O(n) complexity, while the nested approach is O(n²) but handles edge cases better. Choose based on your requirements and constraints.

Updated on: 2026-03-15T23:18:59+05:30

390 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements