Languages
[Edit]
EN

JavaScript - reverse array

4 points
Created by:
Root-ssh
76510

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
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - friendly IT community for everyone.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join