JavaScript Process Array Map in Reverse

In this post, we will explore ways to process JavaScript map on an array in reverse.

For the following examples, we will use this array:

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

1. Reverse the Array Before Map()

As JS reverse mutates the original array, we need to create a new copy that we can reverse and call map on. We can do that using:

Spread Operator

const mapped = [...array].reverse().map(a => a);

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

slice()

const mapped = array.slice(0).reverse().map(a=>a)

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

Another map()

const mapped = array.map(a=>a).reverse().map(a => a);

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

2. Access The Elements In Reverse Order

const mapped = array.map((a, i, arr) => arr[arr.length - 1 - i]);

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

As the map has only three parameters by default, we can add and initialize the fourth parameter and onwards with what we want to use inside the body, such as:

Initialize A Reverse Index

const mapped = array.map((a, i, arr, j = arr.length - 1 - i) => arr[j]);

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

Initialize A Value In Reverse Order

const mapped = array.map((a, i, arr, val = arr[arr.length - 1 - i]) => val);

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

Initialize Both Index And Value In Reverse Order

In case you need both reverse value and index:

const mapped = array.map((a, i, arr, j = arr.length - 1 - i, val = arr[j]) => val*j);

// => [ 90, 72, 56, 42, 30, 20, 12,  6,  2,  0 ]

3. Reverse map() And Keep The Order Intact

You might want to map the array in reverse and keep the original order intact. The above two methods though process the map() in reverse, they don’t maintain the original order. To achieve that, we can simply reverse() after the map() is done.

const mapped = array.map((a, i, arr, j = arr.length - 1 - i, val = arr[j]) => val * j).reverse();
// => [ 0,  2,  6, 12, 20, 30, 42, 56, 72, 90 ]



See also

When you purchase through links on techighness.com, I may earn an affiliate commission.