EN
JavaScript - reverse array
4
points
In this article, we would like to show how to reverse an array in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
var array = ['a', 'b', 'c'];
console.log(array); // ['c', 'b', 'a']
array.reverse();
console.log(array); // ['c', 'b', 'a']
Warning:
reverse()
method works on source array obcject, so sometimes it is safe to create copy before reversion.
Safe reversion example
When we use array
in another place of application, it is safe to use the source array copy.
// ONLINE-RUNNER:browser;
var array = ['a', 'b', 'c'];
var reversedArray = array.slice().reverse();
console.log(array); // ['a', 'b', 'c']
console.log(reversedArray); // ['c', 'b', 'a']
Array
map()
method example
In 2009, ES5 introduced Array.prototype.map()
method that lets us write quick reversion logic with an arrow function.
// ONLINE-RUNNER:browser;
var array = ['a', 'b', 'c'];
var reversedArray = array.map((item, index, array) => array[array.length - index - 1]);
console.log(array); // ['a', 'b', 'c']
console.log(reversedArray); // ['c', 'b', 'a']