Reversing an array of objects in Javascript [duplicate]
Reversing an array of objects in Javascript [duplicate]
This question already has an answer here:
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]
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 ?
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
3 Answers
3
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.
console.log()
Try it this way:
// copy x
y = Object.assign(, x);
console.log(y);
x.reverse();
console.log(x);
It is the job of StackOverflows clean up system to notify the asker about that, not yours :)
– Jonas Wilms
Aug 19 at 13:03
best way to do that is:
var y = [...x].reverse();
var y = [...x].reverse();
var x = ["score":1,"score":2,"score":3]
console.log(x);
var y = [...x].reverse();
console.log(y);
To do what? ...
– Jonas Wilms
Aug 19 at 12:53
clone an array an reverse cloned one @JonasWilms
– Moein Alizadeh
Aug 19 at 12:57
But ... that wasnt the question?
– Jonas Wilms
Aug 19 at 13:00
Sorry @JonasWilms , i think he want to reverse an array without changing original one...
– Moein Alizadeh
Aug 19 at 13:05
I'm expecting the console to show the array in the original order, then in a reversed order. How come?
thats the question.– Jonas Wilms
Aug 19 at 13:08
I'm expecting the console to show the array in the original order, then in a reversed order. How come?
According to MDN here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse
The function reverse()
is destructive
reverse()
it means, the function change the original array, you have to create another variable if you want store the original array like this:
var array1 = ['one', 'two', 'three'];
console.log('array1: ', array1);
// expected output: Array ['one', 'two', 'three']
var reversed = array1.reverse();
console.log('reversed: ', reversed);
// expected output: Array ['three', 'two', 'one']
/* Careful: reverse is destructive. It also changes
the original array */
console.log('array1: ', array1);
// expected output: Array ['three', 'two', 'one']
Thats not the question?
– Jonas Wilms
Aug 19 at 12:53
Please, don't forget to mark this answer as solution if it answered your question. Thanks in advance.
– Lynx 242
Aug 19 at 13:00