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
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]);
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
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
Another solution could be:
const reverseArray = (arr) => arr.map((_, idx, arr) => arr[arr.length - 1 - idx ]);
You basically work with the array indexes
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)