Reverse an array in JavaScript
This post will discuss how to reverse an array in JavaScript.
1. Using Array.prototype.reverse() function
The standard method to reverse an array in JavaScript is using the reverse() method. This method operates in-place, meaning that the original array is modified, and no reversed copy is created.
|
1 2 3 4 5 6 7 |
var arr = [ 1, 2, 3, 4, 5 ]; arr.reverse(); console.log(arr); /* Output: [ 5, 4, 3, 2, 1 ] */ |
If you don’t want to modify the original array, call the reverse() method on a copy of the array. You can clone the array by using slicing or ES6 Spread operator.
|
1 2 3 4 5 6 7 |
var arr = [ 1, 2, 3, 4, 5 ]; var rev = [...arr].reverse(); console.log(rev); /* Output: [ 5, 4, 3, 2, 1 ] */ |
2. Using Array.prototype.map() function
The map() method is often used to create a new array, where each element of it results from some operation applied to elements of another array. To reverse an array, you can do like:
|
1 2 3 4 5 6 7 8 9 |
const reverse = arr => arr.map((_, index) => arr[arr.length - 1 - index]); var arr = [ 1, 2, 3, 4, 5 ]; var rev = reverse(arr); console.log(rev); /* Output: [ 5, 4, 3, 2, 1 ] */ |
The following code uses the Spread operator to clone the array and then uses the map() method to call pop() on the original array and move the returned element to a new array.
|
1 2 3 4 5 6 7 8 9 |
const reverse = arr => [...arr].map(arr.pop, arr); var arr = [ 1, 2, 3, 4, 5 ]; var rev = reverse(arr); console.log(rev); /* Output: [ 5, 4, 3, 2, 1 ] */ |
3. Using Lodash Library
If you’re using the Lodash JavaScript library in your project, you can use the reverse() method to in-place reverse an array.
|
1 2 3 4 5 6 7 8 9 |
var _ = require('lodash'); var arr = [ 1, 2, 3, 4, 5 ]; _.reverse(arr); console.log(arr); /* Output: [ 5, 4, 3, 2, 1 ] */ |
4. Custom Routine
Finally, you can write your own custom routine to reverse an array in-place or return a reverse copy of its instance.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function reverse(arr) { var rev = new Array; for (var i = arr.length - 1; i >= 0; i--) { rev.push(arr[i]); } return rev; } var arr = [ 1, 2, 3, 4, 5 ]; var rev = reverse(arr); console.log(rev); /* Output: [ 5, 4, 3, 2, 1 ] */ |
That’s all about reversing an array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)