How to use map() on an Array in Reverse Order in JS

avatar

Borislav Hadzhiev

Thu Nov 04 20212 min read

banner

Photo by Chad Madden

Use map() on an Array in Reverse Order in JS #

To use the map() method on an array in reverse order:

  1. Use the slice() method to get a copy of the array.
  2. Use the reverse() method to reverse the copied array.
  3. Call the map() method on the reversed array.
index.js
const arr = ['a', 'b', 'c']; const mapReverse1 = arr .slice(0) .reverse() .map(element => { return element; }); console.log(mapReverse1); // ๐Ÿ‘‰๏ธ ['c', 'b', 'a']

The first step is to use the Array.slice method to create a shallow copy of the array.

We do this, because the Array.reverse method changes the contents of the original array in place.

The only parameter we passed to the slice method is the start index - the index of the first element to be included in the new array.

By passing a start index of 0 and no end index, we create a shallow copy of the original array, which we can reverse.

index.js
const arr = ['a', 'b', 'c']; const copy = arr.slice(0); console.log(copy); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c']

The reverse() method reverses an array in place and returns the result.

index.js
const arr = ['a', 'b', 'c']; const reversed = arr.reverse(); console.log(reversed); // ๐Ÿ‘‰๏ธ ['c', 'b', 'a'] console.log(arr); // ๐Ÿ‘‰๏ธ ['c', 'b', 'a']
Notice that the original array stored in the arr variable was also reversed.

This is the reason we created a shallow copy in advance - to avoid changing the original array.

The last step is to use the Array.map method on the reversed array.

An alternative approach is to use the spread syntax (...) to create a shallow copy of the array.

To use the map() method on an array in reverse order:

  1. Use the spread syntax (...) to get a copy of the array.
  2. Use the reverse() method to reverse the copied array.
  3. Call the map() method on the reversed array.
index.js
const arr = ['a', 'b', 'c']; const mapReverse2 = [...arr].reverse().map(element => { return element; }); console.log(mapReverse2); // ๐Ÿ‘‰๏ธ ['c', 'b', 'a']

The spread syntax (...) unpacks the values from the original array into a new array, creating a shallow copy.

We then reverse the copy to avoid mutating the original array and call the map() method on the reversed array.

This approach is a bit more concise than using the slice() method.

Which approach you pick is a matter of personal preference. I'd go with the spread syntax, because it's more readable and intuitive, especially in case the reader of the code is not familiar with the parameters the slice method takes.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee