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

Exception or error:

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?

How to solve:

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(...

###

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)

###

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

###

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 ]

###

Another solution could be:

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

You basically work with the array indexes

###

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

###

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

###

You can do myArray.reverse() first.

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

Leave a Reply

Your email address will not be published. Required fields are marked *