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

后端 未结 10 1043
离开以前
离开以前 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:27

    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(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]))
    }
    

提交回复
热议问题