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

后端 未结 10 1014
离开以前
离开以前 2020-12-23 15:37

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

相关标签:
10条回答
  • 2020-12-23 16:12

    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(...
    
    0 讨论(0)
  • 2020-12-23 16:15

    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]);
    
    0 讨论(0)
  • 2020-12-23 16:16

    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

    0 讨论(0)
  • 2020-12-23 16:20
    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

    0 讨论(0)
  • Another solution could be:

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

    You basically work with the array indexes

    0 讨论(0)
  • 2020-12-23 16:23

    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)

    0 讨论(0)
提交回复
热议问题