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

JavascriptArrays

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

If you don't want to reverse the original array, you can make a shallow copy of it then map of the reversed array,

myArray.slice(0).reverse().map(function(...

Solution 2 - Javascript

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 3 - Javascript

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 4 - Javascript

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 5 - Javascript

Another solution could be:

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

You basically work with the array indexes

Solution 6 - Javascript

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 7 - Javascript

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

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

Solution 8 - Javascript

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 - Javascript

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 10 - Javascript

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 11 - Javascript

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 12 - Javascript

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

Solution 13 - Javascript

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 14 - Javascript

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());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobin NewhouseView Question on Stackoverflow
Solution 1 - JavascriptAdamCooper86View Answer on Stackoverflow
Solution 2 - JavascripttyborgView Answer on Stackoverflow
Solution 3 - Javascriptguest271314View Answer on Stackoverflow
Solution 4 - JavascriptHarryView Answer on Stackoverflow
Solution 5 - JavascriptMatteoView Answer on Stackoverflow
Solution 6 - Javascriptedi9999View Answer on Stackoverflow
Solution 7 - JavascriptAli RazaView Answer on Stackoverflow
Solution 8 - JavascriptdannielumView Answer on Stackoverflow
Solution 9 - JavascriptJackView Answer on Stackoverflow
Solution 10 - JavascriptSimone WestphalView Answer on Stackoverflow
Solution 11 - JavascriptNeeraj TangariyaView Answer on Stackoverflow
Solution 12 - JavascriptIron ManView Answer on Stackoverflow
Solution 13 - JavascriptErbaz KamranView Answer on Stackoverflow
Solution 14 - JavascriptDuong Thanh HopView Answer on Stackoverflow