Created
April 6, 2017 16:49
-
-
Save daartv/288f1fa77b93ce58ea403d90ecbe86e0 to your computer and use it in GitHub Desktop.
Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var productExceptSelf = function(nums) { | |
//Declare a results array | |
var results = []; | |
//iterate through the input array | |
for (var i = 0; i < nums.length; i++) { | |
//Save the value in the current index in a temporary variable | |
var current = nums[i]; | |
//get that number out of the array | |
nums.splice(i,1) | |
//reduce the remaining numbers and push it into results | |
var product = nums.reduce(function (memo, curr, index){ | |
return memo * curr | |
}) | |
results.push(product); | |
//return the number to its position in the original array | |
nums.splice(i, 0, current) | |
} | |
//return the output array | |
return results; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment