10

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 ?

LioM
  • 139
  • 1
  • 2
  • 5

3 Answers3

42

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);
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
Moein Alizadeh
  • 695
  • 5
  • 12
9

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);  
  • Please, don't forget to mark this answer as solution if it answered your question. Thanks in advance. –  Aug 19 '18 at 13:00
-2

According to MDN here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse

The function reverse() is destructive

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']