Instantly share code, notes, and snippets.

Embed
What would you like to do?
Find a product within an array of numbers. Demo at http://jsbin.com/zidogenaro/edit?js,console
var mathManager = {
findProduct: function(product, arr) {
var result = null;
for (var i=0; i<arr.length; i++) {
for (var j=i+1; j<arr.length; j++) {
if (product === arr[i] * arr[j]) {
result = [arr[i], arr[j]];
break;
}
}
if (result) {
break;
}
}
return result;
}
};
var arr = [1, 3, 6, 8, 9, 2, 0, 11, 7];
var result = mathManager.findProduct(18, arr);
console.log('Find product 18 in ' + arr);
console.log(result);
console.log(result.length===2 && result.every(function(v,i) { return v === [3,6][i]; }));
result = mathManager.findProduct(19, arr);
console.log('Find product 19 in ' + arr);
console.log(result);
console.log(result === null);
var result = mathManager.findProduct(22, arr);
console.log('Find product 22 in ' + arr);
console.log(result);
console.log(result.length===2 && result.every(function(v,i) { return v === [2,11][i]; }));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment