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 co
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]))
}
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());
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 ]
You can do myArray.reverse() first.
var myArray = ['a', 'b', 'c', 'd', 'e'];
myArray.reverse().map(function (el, index, coll) {
console.log(el + " ")
});