'Is there a way to use map() on an array in reverse order with javascript?

I want to use the map() function on a javascript array, but I would like it to operate in reverse order.

The reason is, I'm rendering stacked React components in a Meteor project and would like the top-level element to render first while the rest load images below.

var myArray = ['a', 'b', 'c', 'd', 'e'];
myArray.map(function (el, index, coll) {
    console.log(el + " ")
});

prints out a b c d e but I wish there was a mapReverse() that printed e d c b a

Any suggestions?



Solution 1:[1]

Not mutating the array at all, here is a one-liner O(n) solution I came up with:

myArray.map((val, index, array) => array[array.length - 1 - index]);

Solution 2:[2]

You can use Array.prototype.reduceRight()

var myArray = ["a", "b", "c", "d", "e"];
var res = myArray.reduceRight(function (arr, last, index, coll) {
    console.log(last, index);
    return (arr = arr.concat(last))
}, []);
console.log(res, myArray)

Solution 3:[3]

With Named callback function

const items = [1, 2, 3]; 
const reversedItems = items.map(function iterateItems(item) {
  return item; // or any logic you want to perform
}).reverse();

Shorthand (without named callback function) - Arrow Syntax, ES6

const items = [1, 2, 3];
const reversedItems = items.map(item => item).reverse();

Here is the result

enter image description here

Solution 4:[4]

Another solution could be:

const reverseArray = (arr) => arr.map((_, idx, arr) => arr[arr.length - 1 - idx ]);

You basically work with the array indexes

Solution 5:[5]

I prefer to write the mapReverse function once, then use it. Also this doesn't need to copy the array.

function mapReverse(array, fn) {
    return array.reduceRight(function (result, el) {
        result.push(fn(el));
        return result;
    }, []);
}

console.log(mapReverse([1, 2, 3], function (i) { return i; }))
// [ 3, 2, 1 ]
console.log(mapReverse([1, 2, 3], function (i) { return i * 2; }))
// [ 6, 4, 2 ]

Solution 6:[6]

You just need to add .slice(0).reverse() before .map()

students.slice(0).reverse().map(e => e.id)

Solution 7:[7]

Here is my TypeScript solution that is both O(n) and more efficient than the other solutions by preventing a run through the array twice:

function reverseMap<T, O>(arg: T[], fn: (a: T) => O) {
   return arg.map((_, i, arr) => fn(arr[arr.length - i - 1]))
}

In JavaScript:

const reverseMap = (arg, fn) => arg.map((_, i, arr) => fn(arr[arr.length - 1 - i]))

// Or 

function reverseMap(arg, fn) {
    return arg.map((_, i, arr) => fn(arr[arr.length - i - 1]))
}

Solution 8:[8]

You can do myArray.reverse() first.

var myArray = ['a', 'b', 'c', 'd', 'e'];
myArray.reverse().map(function (el, index, coll) {
    console.log(el + " ")
});

Solution 9:[9]

function mapRevers(reverse) {
    let reversed = reverse.map( (num,index,reverse) => reverse[(reverse.length-1)-index] );
    return reversed;
}

console.log(mapRevers(myArray));

I You pass the array to map Revers and in the function you return the reversed array. In the map cb you simply take the values with the index counting from 10 (length) down to 1 from the passed array

Solution 10:[10]

I think put the reverse() key after map is working.

tbl_products
  .map((products) => (
    <div
      key={products.pro_id}
      class="my-1 px-1 w-full md:w-1/2 lg:my-4 lg:px-4 lg:w-1/4 transform transition duration-500 hover:scale-105"
    >
      <article class="overflow-hidden rounded-lg border shadow">
        <a href="#">
          <img
            alt="Placeholder"
            class="block h-auto w-full px-5 pt-3"
            src={products.product_img}
          />
        </a>
      </article>
    </div>
  ))
  .reverse();

In my case, it is working

Solution 11:[11]

var myArray = ['a', 'b', 'c', 'd', 'e'];
var reverseArray = myArray.reverse()
reverseArray.map(function (el, index, coll) {
    console.log(el + " ")
});

Solution 12:[12]

If you are using an immutable array from let's say a redux reducer state, you can apply .reverse() by first making a copy like this:

const reversedArray = [...myArray].reverse();
//where myArray is a state variable

//later in code
reversedArray.map((item, i)=>doStuffWith(item))

Solution 13:[13]

First, you should make a shallow copy of the array, and then use that function on the copy.

[...myArray].reverse().map(function(...

Solution 14:[14]

An old question but for new viewers, this is the best way to reverse array using map

var myArray = ['a', 'b', 'c', 'd', 'e'];
[...myArray].map(() => myArray.pop());