[Interview Question] — Get the product of all the elements of an array except the current Element and return the result as an array!

Input — [2, 3,4,5]

Output — [60, 40,30,24]

Try on your own and leave a reply containing your way of doing so!

Solution — Used Decoder (an Android app) to create this solution because I was lazy enough to not to turn on the laptop 😁


Step 1: Loop through the entire Array using map and not forEach. As I need to return an array (Remember, map() in JavaScript always returns an array and forEach doesn’t)

Step 2: Create a copy of the array for each iteration (Here I have used the Array.slice() but you can use Modern Spread Operator too). Copy of the array is needed as I am going to splice out the current Traversed element which will remove the element from the Given array!

Step 3: use the Index we took out from the second argument from map() and remove the current traversed element.

Step 4: Loop through the remaining elements of the array and start multiplying them and return the result!

There maybe other far more optimised ways to achieve the same thing. I just shared my approach.

Do leave a comment how you should have gone for the solution.