- Related Questions & Answers
- Product of all prime numbers in an Array in C++
- Product of all the Composite Numbers in an array in C++
- Sum of all prime numbers in an array - JavaScript
- First digit in product of an array of numbers in C++
- Product of numbers present in a nested array in JavaScript
- Finding product of an array using recursion in JavaScript
- Find last k digits in product of an array numbers in C++
- Absolute Difference between the Product of Non-Prime numbers and Prime numbers of an Array?
- Compute cartesian product of elements in an array in JavaScript
- Difference between sum and product of an array in JavaScript
- XOR of all Prime numbers in an Array in C++
- Equal partition of an array of numbers - JavaScript
- C++ program to find the first digit in product of an array of numbers
- Return the greatest possible product of n numbers from the array in JavaScript
- Finding all duplicate numbers in an array with multiple duplicates in JavaScript

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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));

The output in the console will be −

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

Advertisements