educative.io

Educative

Alternate solution

One of our users suggested alternate solutions for this problem:

  function findProduct(arr) {
  let zeroCount = 0;
  const arrItemsProduct = arr.reduce((acc, current) => {
    if (current !== 0) {
      return acc * current;
    } else {
      zeroCount++;
      return acc;
    }
  }, 1);
  return arr.map(item => {
    if (zeroCount === 0) {
      return arrItemsProduct / item;
    } else if (zeroCount === 1) {
      return item === 0 ? arrItemsProduct : 0;
    } else {
      return 0;
    }
  });
}

If no 0s are present in arr:

function findProduct(arr) {
  const arrItemsProduct = arr.reduce((acc, current) => acc * current);
  return arr.map(item => arrItemsProduct / item);
}

Alina Fatima | Developer Advocate

2 Likes