I have a question about the solution to this problem. It works, but my question is why do I have to write
stones = stones.slice(0 ,length - 2)
Instead of
stones.slice(0 ,length - 2)
Like sort() and push work without it.
var lastStoneWeight = function (stones) {
stones.sort((a, b) => a - b);
let length = stones.length
if(length <= 1) return stones
let replace = stones[length - 1] - stones[length - 2]
stones = stones.slice(0 ,length - 2) // <----- HERE
stones.push(replace)
if (stones.length > 1) return lastStoneWeight(stones)
return stones
};
console.log(lastStoneWeight([8,10,4])); //return [2]
.sort() and .push() are methods that mutate(modify) your array directly.
.slice() on the other hand, is a method that returns a new array, modified based on your parameters, without even touching the initial one.
stones.slice(0, length-2) is simply returning a value, it's not actually modifying the stones variable. Since it gives you a returned value, you need to assign it to something (in this case stones) or pass it into a function.
stones = stones.slice(0, length-2)
some_func(stones)
or
some_func(stones.slice(0, length-2))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With