Both solutions given by Peter and Rahul should work fine, but they are O(n^2), or solutions with quadratic complexity — note the reduce/forEach inside map.
If you want to find why their solutions are O(n^2), or about BigO notation in general, I recommend you to read this excellent discussion, especially the answers by Todd, and j
Peter's second solution would break for arrays with 0 as an element, because of division by 0 — array.reduce((a, b) => a * b) / element
Having said all that, here is my crack at a better (well that's always subjective, I mean a O(n) :) solution to the above problem:
const calculateDesiredArray = (arr) => {
let zeroIndex = -1;
let nonZeroProduct = 1;
const arrLen = arr.length;
const allZerosArray = Array.from({ length: arrLen }, (v, i) => 0);
for (let i = 0; i < arrLen; i++) {
const ele = arr[i];
if (ele !== 0) {
nonZeroProduct *= ele;
} else {
if (zeroIndex !== -1) { // Encountered a second '0'
// Because of more than 1 '0' element in the array...
// ...all elements in the new array would be '0's
return allZerosArray;
}
// Apart from the element in this index...
// ...all other elements in the new array would be '0's
zeroIndex = i;
}
}
if (zeroIndex !== -1) { // There's a single '0' at this index
// In this case all elements in the new array would be '0'...
// ...except the element at the zeroIndex
const desiredArray = allZerosArray;
desiredArray[zeroIndex] = nonZeroProduct;
return desiredArray;
}
// There are no '0's in the array
const desiredArray = arr.map(ele => nonZeroProduct / ele);
return desiredArray;
};