spaceDog spaceDog - 5 months ago 23
Javascript Question

Product of Array Except Self Javascript

I have been trying implement product of Array Except Self. My initial thought was to use

indexes === array[j]
and
continue
, but it is not working. Can anyone explain why?

var array = [1,2,3,4];
function productOfArrayExceptSelf(array){
var result = 0;
var resultArray = [];
var indexes;
for(var i = 0; i < array.length; i++){
for(var j = 0; j < array.length; j++){
indexes = array[j];
if(indexes === array[j]){
continue;
}
}
}
return result;
}

Answer

You need to compare i with j to know when to continue. Also, you have nowhere a multiplication happening.

Here is a working snippet:

function productOfArrayExceptSelf(array){
    var resultArray = [], product;
    for(var i = 0; i < array.length; i++){
      product = 1;
      for(var j = 0; j < array.length; j++){
         if(i !== j) product *= array[j];
      }
      resultArray.push(product);
    }
    return resultArray;
}

// Sample data
var array = [1,2,3,4];
console.log(productOfArrayExceptSelf(array));

And as a bonus, here is a more compact version, making use of map and reduce:

function productOfArrayExceptSelf(array){
    return array.map(function (_, i) {
        return array.reduce(function (product, val, j) {
            return product * (i === j ? 1 : val);
        }, 1);
    });
}

var array = [1,2,3,4];
console.log(productOfArrayExceptSelf(array));

Comments