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

4 Responses to “Reversing an Array in JavaScript”

  1. Roman FroĊ‚ow says:

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

  2. suggestion says:

    How about using reduceRight?

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

  3. Captain says:

    reduceRight is not available in older JS versions.

  4. Slaven Tomac says:

    Your first function has a lot of errors (syntax as well):

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

    1) after [] should be ; instead of ,
    2) For loop should go to zero included because with this you’ll lose one of your elements
    3) You should return temp, not result

    Here is correct version:

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

Make a Comment