363

Array.prototype.reverse reverses the contents of an array in place (with mutation)...

Is there a similarly simple strategy for reversing an array without altering the contents of the original array (without mutation)?

2

15 Answers 15

678

You can use slice() to make a copy then reverse() it

var newarray = array.slice().reverse();

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

console.log('a', array);
console.log('na', newarray);

7
  • 10
    @Alex slice - If begin is omitted, slice begins from index 0. - so it is the same as array.slice(0) Jun 3, 2015 at 3:55
  • 4
    I think @Alex meant 'explain it in your answer'...regardless...Brilliant solution. Thanks!
    – sfletche
    Jun 3, 2015 at 3:56
  • 66
    I would NOT recommend to use this approach, because it's very misleading practice. It’s very confusing when you use slice() and you actually not slicing anything. If you need immutable reverse, just create fresh new copy: const newArray = [...array].reverse()
    – Oleg Matei
    Jun 27, 2019 at 21:11
  • 11
    Can we all just take a moment to identify how much further JavaScript needs to grow? This is the best we've got? Cmon JavaScript! grow up a little. Aug 30, 2020 at 4:28
  • 9
    @OlegMatei Slicing the whole array is still slicing. It's not confusing if you understand what Array#slice does. There's no reason spread syntax should be any less confusing. Oct 14, 2021 at 1:44
220

In ES6:

const newArray = [...array].reverse()
5
  • 2
    How does the performance of this compare with that of the accepted answer? Are they the same?
    – Katie
    Jan 30, 2019 at 19:47
  • 16
    I'm consistently getting .slice as significantly faster. Jan 31, 2019 at 15:58
  • 10
    @JamesCoyle It's probably browser and OS dependent, but slice is likely to be faster b/c [...] is a generic iterable-to-array so cannot make as many assumptions. As well, it's likely that slice is better optimized b/c it's been around a long time. Jan 31, 2019 at 17:39
  • My thoughts exactly. Jan 31, 2019 at 17:41
  • 2
    See stackoverflow.com/a/52929821/1480587 about benchmarks of different versions for dupicating an array.
    – Peter T.
    Nov 12, 2021 at 21:32
19

const originalArray = ['a', 'b', 'c', 'd', 'e', 'f'];

const newArray = Array.from(originalArray).reverse();

console.log(newArray);

2
  • I like this because the intent is more explicit. Its not obvious that slice() creates a duplicate array.
    – icc97
    Aug 23 at 11:37
  • You can read it as "Create a new array from originalArray then reverse it"
    – icc97
    Aug 23 at 12:02
16

Another ES6 variant:

We can also use .reduceRight() to create a reversed array without actually reversing it.

let A = ['a', 'b', 'c', 'd', 'e', 'f'];

let B = A.reduceRight((a, c) => (a.push(c), a), []);

console.log(B);

Useful Resources:

8
  • 7
    reduceRight is slow af Mar 25, 2018 at 9:15
  • @DragosRizescu Can you share some sample test results? Mar 26, 2018 at 5:14
  • 1
    Here is a repo that you can play with: (not the best example, but had this argument with someone a while ago in a React context, thus I've put it together): github.com/rizedr/reduce-vs-reduceRight Mar 27, 2018 at 15:04
  • 4
    (a, c) => a.concat([c]) feels more idiomatic than (a, c) => (a.push(c), a)
    – Kyle Lin
    Dec 20, 2018 at 23:42
  • 2
    @DragosRizescu it actually looks like this is the fastest of the 3 top answers. jsperf.com/reverse-vs-slice-reverse/3
    – DBosley
    Sep 6, 2019 at 14:45
7

Try this recursive solution:

const reverse = ([head, ...tail]) => 
    tail.length === 0
        ? [head]                       // Base case -- cannot reverse a single element.
        : [...reverse(tail), head]     // Recursive case

reverse([1]);               // [1]
reverse([1,2,3]);           // [3,2,1]
reverse('hello').join('');  // 'olleh' -- Strings too!                              
1
  • 2
    This looks like it would break for empty arrays.
    – Matthias
    Sep 25, 2019 at 9:14
7

There are multiple ways of reversing an array without modifying. Two of them are

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

// Using slice
var reverseArray1 = array.slice().reverse(); // Fastest

// Using spread operator
var reverseArray2 = [...array].reverse();

// Using for loop 
var reverseArray3 = []; 
for(var i = array.length-1; i>=0; i--) {
  reverseArray.push(array[i]);
}

Performance test http://jsben.ch/guftu

2
  • is there any performance difference between array.splice() as you wrote and the slice() method? Dec 7, 2020 at 19:44
  • 2
    It should be slice() and not splice(). The latter returns an empty array.
    – rooch84
    Sep 8, 2021 at 7:58
6

An ES6 alternative using .reduce() and spreading.

const foo = [1, 2, 3, 4];
const bar = foo.reduce((acc, b) => ([b, ...acc]), []);

Basically what it does is create a new array with the next element in foo, and spreading the accumulated array for each iteration after b.

[]
[1] => [1]
[2, ...[1]] => [2, 1]
[3, ...[2, 1]] => [3, 2, 1]
[4, ...[3, 2, 1]] => [4, 3, 2, 1]

Alternatively .reduceRight() as mentioned above here, but without the .push() mutation.

const baz = foo.reduceRight((acc, b) => ([...acc, b]), []);
5

ES2023 Array Method toReversed()

The toReversed() method transposes the elements of the calling array object in reverse order and returns a new array.

const items = [1, 2, 3];
console.log(items); // [1, 2, 3]

const reversedItems = items.toReversed();
console.log(reversedItems); // [3, 2, 1]
console.log(items); // [1, 2, 3]

Browser compatibility

enter image description here

3

There's a new tc39 proposal, which adds a toReversed method to Array that returns a copy of the array and doesn't modify the original.

Example from the proposal:

const sequence = [1, 2, 3];
sequence.toReversed(); // => [3, 2, 1]
sequence; // => [1, 2, 3]

As it's currently in stage 3, it will likely be implemented in browser engines soon, but in the meantime a polyfill is available here or in core-js.

2
const arrayCopy = Object.assign([], array).reverse()

This solution:

-Successfully copies the array

-Doesn't mutate the original array

-Looks like it's doing what it is doing

1

Reversing in place with variable swap just for demonstrative purposes (but you need a copy if you don't want to mutate)

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

1

Jumping into 2022, and here's the most efficient solution today (highest-performing, and no extra memory usage).


For any ArrayLike type, the fastest way to reverse is logically, by wrapping it into a reversed iterable:

function reverse<T>(input: ArrayLike<T>): Iterable<T> {
    return {
        [Symbol.iterator](): Iterator<T> {
            let i = input.length;
            return {
                next(): IteratorResult<T> {
                    return i
                        ? {value: input[--i], done: false}
                        : {value: undefined, done: true};
                },
            };
        },
    };
}

This way you can reverse-iterate through any Array, string or Buffer, without any extra copy or processing for the reversed data:

for(const a of reverse([1, 2, 3])) {
    console.log(a); //=> 3 2 1
}

It is the fastest approach, because you do not copy the data, and do no processing at all, you just reverse it logically.

0

Is there a similarly simple strategy for reversing an array without altering the contents of the original array (without mutation) ?

Yes, there is a way to achieve this by using to[Operation] that return a new collection with the operation applied (This is currently at stage 3, will be available soon).

Implementation will be like :

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

const reversedArr = arr.toReverse();

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

console.log(reversedArr); // [1, 2, 3, 4, 5]
2
  • Uncaught TypeError: arr.toReverse is not a function toReverse is not a thing in JavaScript.
    – Cerbrus
    Sep 15, 2022 at 8:23
  • 1
    @Cerbrus not a thing yet - it's still a proposal which is in the last stage before being finalised. Polyfills are available to preview the functionality: for example here.
    – VLAZ
    Sep 15, 2022 at 8:30
0

Not the best solution but it works

Array.prototype.myNonMutableReverse = function () {
  const reversedArr = [];
  for (let i = this.length - 1; i >= 0; i--) reversedArr.push(this[i]);
  return reversedArr;
};

const a = [1, 2, 3, 4, 5, 6, 7, 8];
const b = a.myNonMutableReverse();
console.log("a",a);
console.log("////////")
console.log("b",b);

-9

es6:

const reverseArr = [1,2,3,4].sort(()=>1)
5
  • 5
    Welcome to SO, Radion! When leaving an answer it's typically a good idea to explain why your answer works and why you came to this conclusion, this helps newer users with understanding the interactions and languages you have specified. Sep 19, 2017 at 14:07
  • In Radion's defense :P that 1 at the end could have been anything greater than zero, because that's how Array.prototype.sort callback (or so called compare function) works. Basically you always compare 2 numbers and in this case the comparison returns always positive so it says always move to the second number in front of the first one :) this is very explanatory: stackoverflow.com/questions/6567941/…
    – iulial
    Feb 18, 2018 at 19:21
  • 9
    sort() mutates the array (i.e., sorts it in place), which is what the OP wants to avoid.
    – clint
    Feb 20, 2018 at 21:02
  • 8
    This answer is wrong in several ways. (1) it mutates the array, as @ClintHarris points out, so it's no better than .reverse(). (2) your comparator is illegal-- when you return 1 for a,b, you must return a negative number for b,a. If your answer reverses the array on some implementations, it's entirely by luck.
    – Don Hatch
    May 30, 2018 at 6:51
  • Please test code when submitting it. At the very least it should do the required task, even if it does mutate the array. This just doesn't work as intended (it doesn't change the array at all) (demo) and is easily corrected with the addition of a single character. Aug 21 at 20:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.