102

I am saving some data in order using arrays, and I want to add a function that the user can reverse the list. I can't think of any possible method, so if anybody knows how, please help.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247

37 Answers37

191

Javascript has a reverse() method that you can call in an array

var a = [3,5,7,8];
a.reverse(); // 8 7 5 3

Not sure if that's what you mean by 'libraries you can't use', I'm guessing something to do with practice. If that's the case, you can implement your own version of .reverse()

function reverseArr(input) {
    var ret = new Array;
    for(var i = input.length-1; i >= 0; i--) {
        ret.push(input[i]);
    }
    return ret;
}

var a = [3,5,7,8]
var b = reverseArr(a);

Do note that the built-in .reverse() method operates on the original array, thus you don't need to reassign a.

Patrick Reck
  • 11,246
  • 11
  • 53
  • 86
Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
61

Array.prototype.reverse() is all you need to do this work. See compatibility table.

var myArray = [20, 40, 80, 100];
var revMyArr = [].concat(myArray).reverse();
console.log(revMyArr);
// [100, 80, 40, 20]
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Rohit Shelhalkar
  • 756
  • 1
  • 9
  • 15
31

Heres a functional way to do it.

const array = [1,2,3,4,5,6,"taco"];

function reverse(array){
  return array.map((item,idx) => array[array.length-1-idx])
}
Jake Boyles
  • 311
  • 3
  • 3
23

20 bytes

let reverse=a=>[...a].map(a.pop,a)
Community
  • 1
  • 1
Torkel Velure
  • 1,217
  • 10
  • 17
  • 1
    Could someone possibly explain this one for me? – user169320 Dec 28 '17 at 05:36
  • 5
    @user169320 `[...a]` clones the array, `.map(a.pop, a)` pops the array (returns the last element of the array) and push it to a new array, which results in a reversed array. – Derek 朕會功夫 Feb 23 '18 at 18:43
  • 3
    ...and the 2nd argument to `map` makes sure that `pop` is executed with `a` as `this`, like as if you would have done `a.pop()` – trincot Jun 20 '18 at 15:06
  • @trincot Why do we have to execute `pop` with `a` as `this`? Could you explain a bit further? – yqbk Aug 13 '18 at 11:12
  • 2
    When you pass on a function reference (so without executing it), which is later used for execution, then that function reference has *no trace at all* of the object you want to have it executed on: it is just a plain function. In the above code you might as well have put `[].pop` instead of `a.pop`: it would be *exactly* the same function. When the implementation of `map` executes that function, it does not know on which array it should be executed. And if you don't tell that, it will fail. The second argument to `map` gives the necessary info to `map`. – trincot Aug 13 '18 at 11:27
  • 2
    is it CodeGolf ? –  Jan 17 '19 at 08:48
  • 2
    Quite clever but bear in mind that this will mutate your original array making it empty (use a deep-freeze before, maybe) – Radu Chiriac Dec 16 '19 at 05:48
  • 1
    what is the purpose of this method, if it mutates the original one and existing `reverse` method is shorter and more clear? The correct solution, whithout mutating of the original array is offered by @parag patel: `a.map(a.pop,[...a]); ` – Alexandr Nov 30 '20 at 10:06
19
const original = [1, 2, 3, 4];
const reversed = [...original].reverse(); // 4 3 2 1

Concise and leaves the original unchanged.

Nick B
  • 657
  • 1
  • 13
  • 33
11
reveresed = [...array].reverse()
Ali Mirzaei
  • 1,496
  • 2
  • 16
  • 27
10

The shortest reverse method I've seen is this one:

let reverse = a=>a.sort(a=>1)
Elia Grady
  • 468
  • 3
  • 16
  • 4
    Doesn’t this depend on how the sorting is implemented? Since the comparing function isn’t consistent (i.e. it always returns 1) the behavior is undefined. – Derek 朕會功夫 Jun 08 '18 at 21:04
  • Actually I was surprised to see it work the way it did. `[1,2,3,4].sort(a=>1)` returns the correct answer for example. The idea is that it closely tied to how the sort method can take a sorting algorithm and since it does it one by one, it's always swaps. – Elia Grady Jun 10 '18 at 19:47
  • The problem with this is that it might not reverse the array with different interpreters. – Derek 朕會功夫 Jun 10 '18 at 20:49
  • 1
    I'm not suggesting this as a good practice, just thought it's an interesting, unconventional take on a well known operation. – Elia Grady Jun 12 '18 at 14:37
6

This is what you want:

array.reverse();

DEMO

qwertymk
  • 34,200
  • 28
  • 121
  • 184
6

**

Shortest reverse array method without using reverse method:

**

 var a = [0, 1, 4, 1, 3, 9, 3, 7, 8544, 4, 2, 1, 2, 3];

 a.map(a.pop,[...a]); 
// returns [3, 2, 1, 2, 4, 8544, 7, 3, 9, 3, 1, 4, 1, 0]

a.pop method takes an last element off and puts upfront with spread operator ()

MDN links for reference:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop

parag patel
  • 2,933
  • 1
  • 10
  • 22
6

two ways:

  1. counter loop

    function reverseArray(a) { 
         var rA = []
         for (var i = a.length; i > 0; i--) {
             rA.push(a[i - 1])
         } 
    
         return rA;
      }
    
  2. Using .reverse()

     function reverseArray(a) {  
         return a.reverse()  
      }
    
Rashid Iqbal
  • 1,123
  • 13
  • 13
5

I've made some test of solutions that not only reverse array but also makes its copy. Here is test code. The reverse2 method is the fastest one in Chrome but in Firefox the reverse method is the fastest.

var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

var reverse1 = function() {
  var reversed = array.slice().reverse();
};

var reverse2 = function() {
  var reversed = [];
  for (var i = array.length - 1; i >= 0; i--) {
    reversed.push(array[i]);
  }
};

var reverse3 = function() {
  var reversed = [];
  array.forEach(function(v) {
    reversed.unshift(v);
  });
};

console.time('reverse1');
for (var x = 0; x < 1000000; x++) {
  reverse1();
}
console.timeEnd('reverse1'); // Around 184ms on my computer in Chrome

console.time('reverse2');
for (var x = 0; x < 1000000; x++) {
  reverse2();
}
console.timeEnd('reverse2'); // Around 78ms on my computer in Chrome

console.time('reverse3');
for (var x = 0; x < 1000000; x++) {
  reverse3();
}
console.timeEnd('reverse3'); // Around 1114ms on my computer in Chrome
Łukasz Jagodziński
  • 3,009
  • 2
  • 25
  • 33
5

Here is a version which does not require temp array.

function inplaceReverse(arr) {
  var i = 0;
  while (i < arr.length - 1) {
    arr.splice(i, 0, arr.pop());
    i++;
  }
  return arr;
}

// Useage:
var arr = [1, 2, 3];
console.log(inplaceReverse(arr)); // [3, 2, 1]
user2914136
  • 83
  • 2
  • 7
  • Doesn’t require a temp array, just Θ(n²) time. This should be done with single swaps. – Ry- Feb 12 '18 at 06:15
5

53 bytes

function reverse(a){
    for(i=0,j=a.length-1;i<j;)a[i]=a[j]+(a[j--]=a[i++],0)
}

Just for fun, here's an alternative implementation that is faster than the native .reverse method.

Community
  • 1
  • 1
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • I always look for that diamond in the rough where the solution is simple, compatible, and concise. You won this question for me, in this case. May you please explain it in detail? – Alexander Dixon Oct 12 '22 at 04:47
5

You can do

var yourArray = ["first", "second", "third", "...", "etc"]
var reverseArray = yourArray.slice().reverse()

console.log(reverseArray)

You will get

["etc", "...", "third", "second", "first"]
4
> var arr = [1,2,3,4,5,6];
> arr.reverse();
  [6, 5, 4, 3, 2, 1]
000
  • 26,951
  • 10
  • 71
  • 101
4
array.reverse() 

Above will reverse your array but modifying the original. If you don't want to modify the original array then you can do this:

var arrayOne = [1,2,3,4,5];

var reverse = function(array){
    var arrayOne = array
    var array2 = [];

    for (var i = arrayOne.length-1; i >= 0; i--){
      array2.push(arrayOne[i])
    } 
    return array2
}

reverse(arrayOne)
enjareyes
  • 43
  • 5
4
function reverseArray(arr) {
    let reversed = [];
    for (i = 0; i < arr.length; i++) { 
    reversed.push((arr[arr.length-1-i]))
    }
  return reversed;
}
aristotll
  • 8,694
  • 6
  • 33
  • 53
Trung Tran
  • 13,141
  • 42
  • 113
  • 200
4

Using .pop() method and while loop.

var original = [1,2,3,4];
var reverse = [];
while(original.length){
    reverse.push(original.pop());
}

Output: [4,3,2,1]

Abhishek
  • 968
  • 10
  • 16
4

I'm not sure what is meant by libraries, but here are the best ways I can think of:

// return a new array with .map()
const ReverseArray1 = (array) => {
    let len = array.length - 1;

    return array.map(() => array[len--]);
}

console.log(ReverseArray1([1,2,3,4,5])) //[5,4,3,2,1]

// initialize and return a new array
const ReverseArray2 = (array) => {
    const newArray = [];
    let len = array.length;

    while (len--) {
        newArray.push(array[len]);
    }

    return newArray;
}

console.log(ReverseArray2([1,2,3,4,5]))//[5,4,3,2,1]

// use swapping and return original array
const ReverseArray3 = (array) => {
    let i = 0;
    let j = array.length - 1;

    while (i < j) {
        const swap = array[i];
        array[i++] = array[j];
        array[j--] = swap;
    }

    return array;
}
console.log(ReverseArray3([1,2,3,4,5]))//[5,4,3,2,1]

// use .pop() and .length
const ReverseArray4 = (array) => {
    const newArray = [];

    while (array.length) {
        newArray.push(array.pop());
    }

    return newArray;
}
console.log(ReverseArray4([1,2,3,4,5]))//[5,4,3,2,1]
WesleyAC
  • 523
  • 6
  • 11
3

Pure functions to reverse an array using functional programming:

var a = [3,5,7,8];

// ES2015
function immutableReverse(arr) {
  return [ ...a ].reverse();
}

// ES5
function immutableReverse(arr) {
  return a.concat().reverse()
}
Zach Barham
  • 457
  • 1
  • 8
  • 18
Faisal Ali
  • 159
  • 2
  • 9
3

As others mentioned, you can use .reverse() on the array object.

However if you care about preserving the original object, you may use reduce instead:

const original = ['a', 'b', 'c'];
const reversed = original.reduce( (a, b) => [b].concat(a) );
//                                           ^
//                                           |
//                                           +-- prepend b to previous accumulation

// original: ['a', 'b', 'c'];
// reversed: ['c', 'b', 'a'];
Michel
  • 26,600
  • 6
  • 64
  • 69
3

It can also be achieved using map method.

[1, 2, 3].map((value, index, arr) => arr[arr.length - index - 1])); // [3, 2, 1]

Or using reduce (little longer approach)

[1, 2, 3].reduce((acc, curr, index, arr) => {
    acc[arr.length - index - 1] = curr;
    return acc;
}, []);
Jaspreet Singh
  • 1,672
  • 1
  • 14
  • 21
3

reverse in place with variable swapping (mutative)

const myArr = ["a", "b", "c", "d"];
for (let i = 0; i < (myArr.length - 1) / 2; i++) {  
    const lastIndex = myArr.length - 1 - i; 
    [myArr[i], myArr[lastIndex]] = [myArr[lastIndex], myArr[i]] 
}
daino3
  • 4,386
  • 37
  • 48
2

Reverse by using the sort method

  • This is a much more succinct method.

const resultN = document.querySelector('.resultN');
const resultL = document.querySelector('.resultL');

const dataNum = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const dataLetters = ['a', 'b', 'c', 'd', 'e'];

const revBySort = (array) => array.sort((a, b) => a < b);

resultN.innerHTML = revBySort(dataNum);
resultL.innerHTML = revBySort(dataLetters);
<div class="resultN"></div>
<div class="resultL"></div>
techmsi
  • 433
  • 1
  • 5
  • 21
  • 1
    This in-place reversal isn’t efficient and the sort method is incorrect (an inconsistent comparison function has implementation-defined behaviour). – Ry- Feb 12 '18 at 06:17
  • In addition to what Ry mentioned, this is an inefficient method considering in-place changes can be done in O(n/2), because you only need to really transverse half the array. Sort function's time complexity is O(n log n), which is worse than even an O(n) solution. – iPzard Jan 27 '21 at 16:49
2

Using ES6 rest operator and arrow function.

const reverse = ([x, ...s]) => x ? [...reverse(s), x] : [];
reverse([1,2,3,4,5]) //[5, 4, 3, 2, 1]
Ankit Sinha
  • 1,630
  • 1
  • 20
  • 19
2

Use swapping and return the original array.

const reverseString = (s) => {
  let start = 0, end = s.length - 1;
  while (start < end) {
    [s[start], s[end]] = [s[end], s[start]]; // swap
    start++, end--;
  }
  return s;
};

console.log(reverseString(["s", "t", "r", "e", "s", "s", "e", "d"]));
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
1

Infact the reverse() may not work in some cases, so you have to make an affectation first as the following

let a = [1, 2, 3, 4];
console.log(a);  // [1,2,3,4]
a = a.reverse();
console.log(a); // [4,3,2,1]

or use concat

let a = [1, 2, 3, 4];
console.log(a, a.concat([]).reverse());  // [1,2,3,4], [4,3,2,1]
Smaillns
  • 2,540
  • 1
  • 28
  • 40
0

What about without using push() !

Solution using XOR !

var myARray = [1,2,3,4,5,6,7,8];

function rver(x){
    var l = x.length;
    for(var i=0; i<Math.floor(l/2); i++){

        var a = x[i];
        var b = x[l-1-i];

        a = a^b;
        b = b^a;
        a = a^b;

        x[i] = a;
        x[l-1-i] = b;
    }

    return x;

}

console.log(rver(myARray));
ErcanE
  • 1,571
  • 3
  • 19
  • 28
0

JavaScript already has reverse() method on Array, so you don't need to do that much!

Imagine you have the array below:

var arr = [1, 2, 3, 4, 5];

Now simply just do this:

arr.reverse();

and you get this as the result:

[5, 4, 3, 2, 1];

But this basically change the original array, you can write a function and use it to return a new array instead, something like this:

function reverse(arr) {
  var i = arr.length, reversed = [];
  while(i) {
    i--;
    reversed.push(arr[i]);
  }
  return reversed;
}

Or simply chaning JavaScript built-in methods for Array like this:

function reverse(arr) {
  return arr.slice().reverse();
}

and you can call it like this:

reverse(arr); //return [5, 4, 3, 2, 1];

Just as mentioned, the main difference is in the second way, you don't touch the original array...

Alireza
  • 100,211
  • 27
  • 269
  • 172
0

How about this?:

  function reverse(arr) {
    function doReverse(a, left, right) {
      if (left >= right) {
        return a;
      }
      const temp = a[left];
      a[left] = a[right];
      a[right] = temp;
      left++;
      right--;
      return doReverse(a, left, right);
    }

    return doReverse(arr, 0, arr.length - 1);
  }

  console.log(reverse([1,2,3,4]));

https://jsfiddle.net/ygpnt593/8/

techguy2000
  • 4,861
  • 6
  • 32
  • 48
0

This function will work with arrays that may have gaps between their indices.

function reverse( a ) {
    var b = [], c = [] ;
    a.forEach( function( v ) { b.push( v ) } ) ;
    a.forEach( function( v, i ) { c[i] = b.pop() } ) ;
    return c ;
}

var a= [] ; a[1] = 2 ; a[3] = 4 ; a[7] = 6 ; a[9] = 8 ;
a = reverse( a ) ;
var s = '' ;
a.forEach( function( v, i ) { s += 'a[' + i + '] = ' + v + '  ' } ) ;
console.log( s ) ;
// a[1] = 8  a[3] = 6  a[7] = 4  a[9] = 2
barncat
  • 87
  • 1
  • 4
0

Below is a solution with best space and time complexity

function reverse(arr){
let i = 0;
let j = arr.length-1; 
while(i<j){
arr[j] = arr[j]+arr[i];
arr[i] = arr[j] - arr[i];
arr[j] = arr[j] - arr[i];
i++;
j--;
}
return arr;
}
var arr = [1,2,3,4,5,6,7,8,9]
reverse(arr);

output => [9,8,7,6,5,4,3,2,1]

saransh mehra
  • 157
  • 2
  • 9
0

reverse array and sub-array (in place) with ES6.

function reverse(array, i=0, j=array.length-1){
  while (i < j){
    [array[i], array[j]] = [array[j], array[i]];
    ++i;
    --j;
  }
}
QuentinUK
  • 2,997
  • 21
  • 20
0

We have reverse() function to reverse the given array in JS.

var a = [7,8,9];
a.reverse(); // 9 8 7

function reverseArr(input) 
{
var ret = new Array;
for(var i = input.length-1; i >= 0; i--) 
{
    ret.push(input[i]);
}
return ret;
}
Apps Maven
  • 1,314
  • 1
  • 4
  • 17
0

I also faced the same problem. Thank you for this question. I did the code like the below snippet. It works nicely. I used ES6.

const Array = ["a", "b", "c", "d"];
let revArray = [].concat(Array).reverse();

when I console.log it I got the output like below

console.log(revArray)
// output: ["d","c","b","a"]
Sabesan
  • 654
  • 1
  • 10
  • 17
  • Why would you name your array `Array`? It is easily confused with keywords, and capitalising the first letter of a regular variable, while possible, it's against all conventions/best practices. Reserve that notion for signaling classes, etc. – SherylHohman Aug 16 '20 at 16:47
0
array.slice().reverse();

Leaves the original array unchanged.

Nick B
  • 657
  • 1
  • 13
  • 33
-1

I just rewrote the haskell implementation to js.

const rev = (list, reversed) => {
    if (list.length == 0) return reversed

    reversed.unshift(list[0])
    return rev(list.slice(1), reversed)
}

const reverse = (list) => rev(list, [])
TaoJS
  • 109
  • 1
  • 2
  • 13
  • This implementation is seriously inefficient in JS, since arrays aren’t linked lists. – Ry- Aug 22 '18 at 03:34