JS: code challenge review from Interview Cake
I had this pretty easy code challenge which i found on Interview Cake:
You have an array of integers, and for each index you want to find the product of every integer except the integer at that index.Write a function get_products_of_all_ints_except_at_index() that takes an array of integers and returns an array of the products.For example, given:
[1, 7, 3, 4]
your function would return:
[84, 12, 28, 21]
by calculating:
[7 * 3 * 4, 1 * 3 * 4, 1 * 7 * 4, 1 * 7 * 3]
Do not use division in your solution.
The answer is already given. So what i need to do is just to write function which return the same answer. But i took me time to solve it, because i didn’t know some nuances of cloning an array and removing elements.
My pseudo code is:
- Create an empty array.
- Make a copy of the original array.
- Run Iteration. On each loop remove an element with current index, find the product of remained elements. Push the result into the new array.
- Outside of iteration return the new array.
It’s so easy, I should be embarrassed to write this post. But i’m not!
Step-by-step
Copy of array
How do you usually make a copy of an array? You can’t just do
var clonedArray = originalArray;Because as soon as you change your clonedArray, your originalArray will be also changed.
To clone the contents of a given array, all you need to do is call slice(), providing 0 as the first argument:
var clonedArray = originalArray.slice(0)and after that you can do anything you want with clonedArray and your originalArray will remain the same.
Removing elements
i used splice() method for removing an element with particular index.
If you want to remove elements, splice() takes two arguments: index and number of elements you want to remove:
var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
myFish.splice(2, 1); // remove 1 item at 2-index position (that is, "drum")
// myFish is ["angel", "clown", "mandarin", "sturgeon"]Multiplying remaining elements
I used reduce() method which takes callback function as an argument.
The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
var result = [1, 7, 3, 4].reduce(
(product, element) => product * element
)Pushing to a new array
Very easy, but i can’t skip this step in this post. I used push() method to add the result at the end of new array.
newarray.push(result)And my code looks like this:
function challenge(array){
newArray = []
for(let i = 0; i < array.length; i++){
var copy = array.slice(0)
copy.splice(i, 1)
var result = copy.reduce(
(product, element) => product * element
)
newArray.push(result)
}
return newArray
}challenge([1, 7, 3, 4]) #=> [ 84, 12, 28, 21 ]
Good luck