Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
128
rated 0 times [  135] [ 7]  / answers: 1 / hits: 24719  / 6 Years ago, sun, august 19, 2018, 12:00:00

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 ?


More From » arrays

 Answers
111

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

[#53702] Wednesday, August 15, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austonjuancarlosb

Total Points: 238
Total Questions: 89
Total Answers: 99

Location: Chad
Member since Mon, Dec 5, 2022
1 Year ago
;