Languages
[Edit]
EN

JavaScript - reverse array

4 points
Created by:
Root-ssh
7587

In this article we would like to show how to reverse array in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

var array = ['a', 'b', 'c'];
var reversedArray = array.reverse();

function print(array) {
	console.log(array.join(' ')); 
}

print(array);         // c b a   <------  Pay attention or use copy !!!
print(reversedArray); // c b a

Note: be careful reversing array because reverse() method works on source array obcject. It is safe to call array.slice().reverse().

Safe reversion example

When we use array in other place of application it is safe to use sourse array copy.

// ONLINE-RUNNER:browser;

var array = ['a', 'b', 'c'];
var reversedArray = array.slice().reverse();

function print(array) {
	console.log(array.join(' ')); 
}

print(array);         // a b c
print(reversedArray); // c b a

Array map() method example

In 2009, ES5 intoduced Array.prototype.map() method that let us to write quick reversion logic with arrow function.

// ONLINE-RUNNER:browser;

var array = ['a', 'b', 'c'];
var reversedArray = array.map((item, index, array) => array[array.length - 1 - index]);

function print(array) {
	console.log(array.join(' ')); 
}

print(array);         // a b c
print(reversedArray); // c b a
Hey 👋
Would you like to know what we do?
  • Dirask is online IT community for professionals and hobbyist to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.