JavaScript Challenge - Product of Everything Else

This community-built FAQ covers the “Product of Everything Else” code challenge in JavaScript. You can find that challenge here, or pick any challenge you like from our list.

Top Discussions on the JavaScript challenge Product of Everything Else

There are currently no frequently asked questions or top answers associated with this challenge – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this challenge. Ask a question or post a solution by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this challenge, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

Looking for motivation to keep learning? Join our wider discussions in #community

Learn more about how to use this guide.

Found a bug? Report it online, or post in #community:Codecademy-Bug-Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

The following works by iterating the array, making a shallow copy and then setting the current element to 1, then computing the product. No elements are ever removed or replaced in the initial array.

function productOfTheOthers(array) {
  const mul = (a, b) => a * b
  const arr = []
  array.forEach((x, i) => {
    const u = array.slice()
    u[i] = 1
    arr.push(u.reduce(mul))
  })
  return arr
}

console.log(productOfTheOthers([1, 2, 3, 4, 5]))

// Leave this so we can test your code:
module.exports = productOfTheOthers;
function productOfTheOthers(array) {
  let currentIndex = 0;
  let productArray = [];

  while(currentIndex !== array.length) {
    let productSum = 1;
    let arrayOfProducts = array.filter((_, index) => index !== currentIndex);
    for (let num of arrayOfProducts) productSum *= num;
    productArray.push(productSum);
    currentIndex += 1;
  }
  return productArray;
}


console.log(productOfTheOthers([1, 2, 3, 4]))
console.log(productOfTheOthers([5, 5, 5]))

// Leave this so we can test your code:
module.exports = productOfTheOthers;

This function has (I think - correct me if I am wrong) a time complexity of O(N), linear time, due to no nested loops. It calculates cumulative products in both directions for the array. Then these 2 cumulative products are used to calculate the product of missing numbers:

function productOfTheOthers(array) {
  // Calculate forward and reverse cumulative products:
  const fwdProd = [array[0]];
  const revProd = [array[array.length - 1]];
  for (let i = 1; i < array.length; i++) {
    fwdProd.push(fwdProd[i - 1] * array[i]);
    revProd.push(revProd[i - 1] * array[array.length - 1 - i]);
  }
  // Map over the array once and multiply from the cumulative product arrays:
  return array.map((nr, idx) => {
    const fact1 = idx >=1 ? fwdProd[idx - 1] : 1;
    const fact2 = idx < revProd.length - 1 ? revProd[revProd.length - idx - 2] : 1;
    return fact1 * fact2;
  });
}

And that is my code:
function productOfTheOthers(array) {
// Write your code here
let result = ;
for (let i = 0; i < array.length; i++) {
let product = 1;
for (let j = 0; j < array.length; j++) {
if (i === j) continue;
else {
product *= array[j];
}
}
result.push(product);
}
return result;
}
console.log(productOfTheOthers([1, 2, 3, 4, 5]))

// Leave this so we can test your code:
module.exports = productOfTheOthers;

Hello,
Why is my code not passing the challenge (3/5 tests passed) ?

function productOfTheOthers(array) {
  let result = [];
  const reducer = (previousValue, currentValue) => previousValue * currentValue;
  array.forEach((value, index) => {
      result[index] = array.reduce(reducer) / value;
    });

  return result;
}
console.log(productOfTheOthers([1, 2, 3, 4, 5]))

// Leave this so we can test your code:
module.exports = productOfTheOthers;
function productOfTheOthers(array) { let result = []; const reducer = (previousValue, currentValue) => previousValue * currentValue; array.forEach((value, index) => { result[index] = array.reduce(reducer) / value; }); return result; } console.log(productOfTheOthers([1, 2, 3, 4, 5])) // Leave this so we can test your code: module.exports = productOfTheOthers;

Probably because JS and large numbers can act a little strange sometimes. Try your code with an array such as [999999, 999999, 999999]. It will return a decimal output and not an integer. I usually try to avoid division for problems such as this one as the potential is there for a decimal output when it should be an integer.

function productOfTheOthers(array) {
  let result = [];
 array.forEach(function(el, index) {
    let somme = 1;
    array.forEach(function(elmt, ind) {
      if (index !== ind) {
        somme *= elmt
      }
    })
    result.push(somme)
  })
  return result;
}
console.log(productOfTheOthers([5, 5, 5]))

// Leave this so we can test your code:
module.exports = productOfTheOthers;

You right. I rewrote the code and got rid of division operation. I have instead used outer and inner forEach loop and now it seems to work.

function productOfTheOthers(array) {
  let result = [];
  const reducer = (previousValue, currentValue) => previousValue * currentValue;
  array.forEach((outVal, outInd) => {
      
      // this line bellow may work also but does not pass the test
      //result[index] = array.reduce(reducer) / value;

      let product = 1; // initial value of product
      array.forEach((inVal, inInd) => {
        if(outInd !== inInd) {
          product = product * inVal; // calculating products
        }
      });
      result.push(product); // adding products
    });

  return result;
}
console.log(productOfTheOthers([1, 2, 3, 4, 5]))

// Leave this so we can test your code:
module.exports = productOfTheOthers;
1 Like

function productOfTheOthers(array) {
  const getProduct = a => a.reduce((p,c) => p * c);
  return array.map((_,i) => getProduct(array.filter((_,j) => i !== j)));
}

1 Like

set one of your array values to 0 and it will break (can’t divide by zero)

1 Like

Only if it cannot handle NaN (0 / 0) or Infinity (42 / 0). The code will run to completion but we may not like the result. Recall that NaN and Infinity are both Number in JS.

yep, fair enough, “break” is prob not the right word here. provides the wrong answer.

1 Like