javascript – Invert array order

Question:

I have the array:

var meuArray = [1, 2, 5, 7, 9, 4];

How to reverse the order so that it looks like this:

[4, 9, 7, 5, 2, 1]

Answer:

As other answers have already indicated, you can use the array's reverse method. But beware that this changes the original array, and there are times when it is necessary to have a copy.

To avoid changing the original array, you can use slice first. This method is done to generate a new array that is a "slice" of the original. But if you pass 0 as the first argument, that slice will be a clone of the original full array:

var meuArray = [1, 2, 5, 7, 9, 4];
var meuArrayInvertido = meuArray.slice(0).reverse();
Scroll to Top