Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use " = " for an array method?

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]
like image 471
Jkaram Avatar asked Feb 13 '26 16:02

Jkaram


2 Answers

.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.

like image 150
Michalis Garganourakis Avatar answered Feb 16 '26 04:02

Michalis Garganourakis


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))
like image 23
SteveK Avatar answered Feb 16 '26 04:02

SteveK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!