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?
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.
The Map object holds key-value pairs and remembers the original insertion order of the keys.
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(...
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]);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With