Reputation: 25
Example: If we have array = [1,2,5,10];
output should be [100,50,20,10];
So, in each iteration escape the current element of iteration.
Upvotes: 1
Views: 132
Reputation: 68
My suggestion
[1,2,5,10].map((x, i, arr) => arr.reduce((acc, y, j) => (i !== j) ? acc * y : acc, 1));
Upvotes: 1
Reputation: 89374
You can first find the total product and then divide that by the current element in each iteration.
const arr = [1,2,5,10];
const product = arr.reduce((acc,curr)=>acc*curr,1);
const res = arr.map(x => product / x);
console.log(res);
Upvotes: 4