Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 910
Robin Newhouse Avatar asked Apr 05 '16 02:04

Robin Newhouse


People also ask

Can you map in reverse in JavaScript?

To reverse the order of a Map object: Use the Array. from() method to convert the Map to array. Call the reverse() method to reverse the array.

Does map retain order JavaScript?

The Map object holds key-value pairs and remembers the original insertion order of the keys.


3 Answers

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(...
like image 72
AdamCooper86 Avatar answered Oct 13 '22 09:10

AdamCooper86


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]);
like image 43
tyborg Avatar answered Oct 13 '22 07:10

tyborg


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)
like image 25
guest271314 Avatar answered Oct 13 '22 07:10

guest271314