Languages
[Edit]
EN

JavaScript - reverse array

4 points
Created by:
Root-ssh
175020

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

Alternative titles

  1. JavaScript - reverse array without using external libraries
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join