Pavle Ilic
Pavle Ilic

Reputation: 25

how to multiply all elements in a sequence but in each iteration to omit the current element (javascript)?

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

Answers (2)

Serhii Pemakhov
Serhii Pemakhov

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

Unmitigated
Unmitigated

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

Related Questions