Reverse array order

Asked

Viewed 8,511 times

9

I have the array:

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

How to reverse the order so it stays the following way:

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

5 answers

12


As other responses have indicated, you can use the method reverse array. But note 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 the slice before. This method is done to generate a new array that is a "slice" of the original. But if you pass 0 as a first argument, this slice will be a clone of the complete original array:

var meuArray = [1, 2, 5, 7, 9, 4];
var meuArrayInvertido = meuArray.slice(0).reverse();
  • +1, had forgotten the possibility to use Slice to clone the array.

  • I ended up using your solution. Just to understand better, with the slice works because I am creating a new array and I do the reversal in this new array, that’s right?

  • 2

    @Pedrocamarajunior, the slice functions as a substring, but with Array, by making a slice(0, null) it is creating a second array with the elements from Indice 0 to the end of the array, i.e. slice(0) will clone the original array.

7

Pedro, despite the Array.prototype.reverse work in your example, it will mutate the original array, so if you make a console.log(meuArray) you will notice that the same will be reversed.

var output = document.getElementById("output")
var log = function (object) {
  var container = document.createElement("div");
  container.textContent = JSON.stringify(object);
  output.appendChild(container);
}

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

var meuArrayInvertido = meuArray.reverse();
log(meuArray);

log(meuArrayInvertido);
<div id="output">
</div>

In this case it doesn’t make much sense to instantiate an object meuArrayInvertido, since the original array was inverted as well. so in this case you can use the Array.prototype.map to do the job.

var output = document.getElementById("output")
var log = function (object) {
  var container = document.createElement("div");
  container.textContent = JSON.stringify(object);
  output.appendChild(container);
}

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

var meuArrayInvertido = meuArray.map(function (item, indice, array){
  return array[array.length - indice - 1];
});
log(meuArray);

log(meuArrayInvertido);
<div id="output">
</div>

  • Thanks for the explanation, I had not connected me of that question. Anyway I ended up using the solution of @bfavaretto

  • @Pedrocamarajunior, the bfavaretto solution is very good, I would also use his ;D

4

You can use a cycle for and exchange elements of the elements:

var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
alert(array);
var length = array.length;
var left = null;
var right = null;
for (left = 0, right = length - 1; left < right; left += 1, right -= 1) {
  var temporary = array[left];
  array[left] = array[right];
  array[right] = temporary;
}
alert(array);

(Behold here the comparison between this method and .reverse() in terms of performance).

In terms of readability and complexity, if you are dealing with arrays small and slightly inverted, the .reverse() and simpler. However, if you are critical of the inversion performance, use the cycle method.

4

Like the Tobymosque responded, on the amendment in array, I developed another alternative for the occasion.

I set a function for the prototype Array, this function handles the this, which is nothing more than the variable of "type" Array calling the function, and with a for decreasing, using the function push() to create a new array with the inverted order returning at the end of the function.

var arr = [1,2,3,4,5];

// Define uma função no prototipo do Array
// para retornar o mesmo com valores em orderm invertida.
Array.prototype.inverter = function() {
  var arr = [];
  for(i = this.length - 1; i >= 0; i--) {
     arr.push(this[i]);
  }
  return arr;
}

var nArr = arr.inverter();

// Saida de dados.
document.writeln(
  JSON.stringify(arr),
  JSON.stringify(nArr)
);

3

A way I found and using the re-verse

var meuArray = [1, 2, 5, 7, 9, 4];
var meuArrayInvertido = meuArray.reverse();
//meuArrayInvertido === [4, 9, 7, 5, 2, 1]
  • 1

    Please note that the array original also and reversed in this way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.