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

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

提交回复
热议问题