Map and Sort in one iteration in Javascript?

后端 未结 1 1638
一向
一向 2021-01-18 15:33

Is it possible to map an array to a new array and to sort it at the same time without iterating twice (once for the map on the first array and once for the sort on the secon

相关标签:
1条回答
  • 2021-01-18 16:08

    Sorting generally takes more than one iteration by itself. It's almost certainly O(n log n) for the average case (the algorithm isn't specified by ECMAScript, but that's the best you can do with a comparison sort), so there's not much point in doing both at the same time.

    You can chain them into one expression though, since sort returns the array itself:

    function order(a, b) {
        return a < b ? -1 : (a > b ? 1 : 0);
    }
    var arr2 = arr.map(function(item) { ... }).sort(order);
    
    0 讨论(0)
提交回复
热议问题