I am Hack Sparrow
Captain of the Internets.

Reversing an Array in JavaScript

How do you reverse an array in JavaScript?

Reversing an array in JavaScript is pretty straightforward: the JavaScript Array object comes with a method that does the reversing natively. The usage example is given below:

var a = ['AC/DC', 'Aerosmith', 'GNR'];
console.log(a); // ["AC/DC", "Aerosmith", "GNR"]
a.reverse();
console.log(a); // ["GNR", "Aerosmith", "AC/DC"]

Note: the Array.reverse method is destructive, meaning it will modify the array you call the method on.

For huge arrays, writing custom reversing functions make the process faster. A simple implementation of custom array reversal function is given below:

function reverse(a) {
    var temp = [],
    var len = a.length;
    for (var i = (len - 1); i !== 0; i--) {
        temp.push(a[i]);
    }
    return result;
}

The above function preserves the original array and returns a reversed copy. It can be easily modified to alter the original array. To do that just set the value of a to temp and return a.

Here is another JavaScript function to reverse an array. This one is obviously faster than the one above, it is also destructive. But it can be made non-destructive using the technique in the first function.

function reverse(a) {
    var i = 0;
    var j = a.length - 1;

    while (i < j) {
        var x = a[i];
        a[i] = a[j];
        a[j] = x;

        i++;
        j--;
    }
}

So those were the ways to reverse arrays in JavaScript. I would recommend sticking with the native reverse method unless there is a critical requirement for performance.

Reference

JavaScript Array

3 Responses to “Reversing an Array in JavaScript”

  1. Roman FroĊ‚ow on December 6th, 2011 at 6:12 pm

    function reverse(a) {
    var temp = [];
    var len = a.length;
    for (var i = (len – 1); i !== 0; i–) {
    temp.push(a[i]);
    }
    return temp;
    }


  2. How about using reduceRight?

    function reverseArray(array)
    {
    let emptyArr = [];
    return array.reduceRight(function(nArray,element){
    nArray.push(element+1);
    return nArray;
    },emptyArr);
    }


  3. reduceRight is not available in older JS versions.

Make a Comment