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 ?
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);
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);
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