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

后端 未结 10 1015
离开以前
离开以前 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<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]))
    }
    
    0 讨论(0)
  • 2020-12-23 16:29

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

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

    You can do myArray.reverse() first.

    var myArray = ['a', 'b', 'c', 'd', 'e'];
    myArray.reverse().map(function (el, index, coll) {
        console.log(el + " ")
    });
    
    0 讨论(0)
提交回复
热议问题