Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing an array of objects in Javascript [duplicate]

As the title says, I'd like to reverse an array made of objects in Javascript.

Example : var x = [{"score":1},{"score":2},{"score":3}]

To do so, I'm using the .reverse() method.

Now, let's say I write this code

console.log(x);
x.reverse();
console.log(x);

I'm expecting the console to show the array in the original order, then in a reversed order. However, It really shows both arrays in the reversed order.

How come ?

like image 566
LioM Avatar asked Mar 02 '26 01:03

LioM


2 Answers

Best way to do that is var y = [...x].reverse(). See the snippet:

var x = [{"score":1},{"score":2},{"score":3}]
var y = [...x].reverse();
console.log(x);
var y = [...x].reverse();
console.log(y);
like image 131
Moein Alizadeh Avatar answered Mar 04 '26 15:03

Moein Alizadeh


console.log() takes into account whether a mutable object has changed before it has been printed on the screen. And as your process of OUTPUT -> CHANGE -> OUTPUT is almost plesiochronous, both outputs are the same. You have to use a copy of x in order to get the prompt you need.

Try it this way:

// copy x
y = Object.assign({}, x);
console.log(y);

x.reverse();
console.log(x);