How do I keep an original copy when using Sort in Javascript arrays?

Asked

Viewed 60 times

4

I need to sort an array, but I can’t miss the original sequence.

To do this, I created a new variable and assigned the value to it, making a copy of the original. However, when using the method sort, realized that it modifies the two variables. Follows the code excerpt:

var rank = [292, 130, 55, 232, 213, 62, 152], rankOdered = [];
rankOrdered = rank;

console.log("rankOdered: " + rankOrdered)
console.log("rank: " + rank)
console.log("")

rankOrdered.sort(function (a, b) { return b - a });

console.log("rankOdered: " + rankOrdered)
console.log("rank: " + rank)

On the console screen:

rankOdered: 292,130,55,232,213,62,152
rank: 292,130,55,232,213,62,152
<empty string>
rankOdered: 292,232,213,152,130,62,55
rank: 292,232,213,152,130,62,55

1 answer

6


This is because you are not actually making a copy of the array. Note here:

var rank = [292, 130, 55, 232, 213, 62, 152];
var rankOrdered = rank;

When you do var rankOrdered = rank, you are attributing, to rankOrdered, the reference of the original array, which in this case is rank.

Therefore, any modifications made to the array rankOrdered will also be reflected in the array rank (and vice versa), since the two variables point to the same object (yes, arrays are objects in Javascript).

And what happens is that the method Array.prototype.sort does not make modifications to a new array. O sort makes the modifications in-place. Thus, the sort modify the array applied to it.

So what you need to do is make a copy of it. There are various forms to do this. For example, using the Operator spread:

var rank = [292, 130, 55, 232, 213, 62, 152];
var rankOrdered = [...rank]; // Agora sim, cria-se um novo array.

rankOrdered.sort((a, b) => b - a);

console.log(rank);
console.log(rankOrdered);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.