Sorting an array of objects in Chrome

后端 未结 3 1610
傲寒
傲寒 2020-12-01 09:21

EDIT: As noted by kennytm below and after investigating myself, according to the ECMA spec, when two objects are determined to be equal in a custom sort, JavaScript is

相关标签:
3条回答
  • 2020-12-01 09:57

    The ECMAScript standard does not guarantee Array.sort is a stable sort. Chrome (the V8 engine) uses in-place QuickSort internally (for arrays of size ≥ 22, else insertion sort) which is fast but not stable.

    To fix it, make customSort compare with .b as well, eliminating the need of stability of the sorting algorithm.

    0 讨论(0)
  • 2020-12-01 10:03

    The V8 sort is not stable, unfortunately. I'll see if I can dig up the Chromium bug about this.

    V8 sort is now stable!

    0 讨论(0)
  • 2020-12-01 10:09

    May be you know it already but you can use an array to sort on multiple columns and avoid this bug:

    var customSort = function(a,b) {
        return [a.a, a.b] > [b.a, b.b] ? 1:-1;
    }
    
    0 讨论(0)
提交回复
热议问题