Chrome稳定排序功能

时间:2017-11-10 06:01:27

标签: javascript

我想让Chrome的Array.sort()功能保持稳定。我知道还有其他库实现了一个稳定的排序,但是我试图让本地Array.sort()保持稳定,因为我正在使用一些其他库来监听sort()函数来触发动画,但是它在Chrome上变得不稳定,因为它不稳定。

 myArray.sort(function (a, b) {
    if (a.someVal > b.someVal) return -1
    else if (a.someVal < b.someVal) return 1
    //return 0  I shouldn't return 0 as its order will be randomise by chrome

    // My hack around idea was to somehow track their index but this is not working, probably while sorting is ongoing, looking up the index gets messed up? IDK.
     let aIndex = myArray.findIndex(x => x.id === a.id)
     let bIndex = myArray.findIndex(x => x.id === b.id)
     return aIndex < bIndex ? -1 : 1
  })

任何人都知道如何让chrome的排序功能保持稳定?

示例,让我们按b排序,减少。 给定

[
{'a':1,'b':1},
{'a':2,'b':1},
{'a':3,'b':1},
{'a':4,'b':1},
{'a':5,'b':1},
{'a':6,'b':1},
{'a':7,'b':2},
]

预期稳定排序

[
{'a':7,'b':2},
{'a':1,'b':1},
{'a':2,'b':1},
{'a':3,'b':1},
{'a':4,'b':1},
{'a':5,'b':1},
{'a':6,'b':1}
]

Chrome的不稳定排序

[
{'a':7,'b':2},
{'a':4,'b':1},
{'a':3,'b':1},
{'a':2,'b':1},
{'a':1,'b':1},
{'a':6,'b':1},
{'a':5,'b':1}
]

1 个答案:

答案 0 :(得分:2)

首先获取包含索引的数组:

const withIndexes = myArray.map(
    (x, i) => ({index: i, value: x}));

创建一个函数来对多个比较进行排序:

const compareAll = (...comparisons) => (a, b) =>
    comparisons.reduce((m, f) => m || f(a, b), 0);

也可以使用< / >来比较某些值:

const compareDefault = (a, b) =>
    a < b ? -1 :
    a > b ? 1 :
    0;

按值排序,然后按索引排序:

withIndexes.sort(compareAll(
    (a, b) => -compareDefault(a.value.someVal, b.value.someVal),
    (a, b) => compareDefault(a.index, b.index),
));

再次获取值:

const sorted = withIndexes.map(x => x.value);

用你的例子:

const compareAll = (...comparisons) => (a, b) =>
    comparisons.reduce((m, f) => m || f(a, b), 0);

const compareDefault = (a, b) =>
    a < b ? -1 :
    a > b ? 1 :
    0;

const myArray = [
    {'a':1,'b':1},
    {'a':2,'b':1},
    {'a':3,'b':1},
    {'a':4,'b':1},
    {'a':5,'b':1},
    {'a':6,'b':1},
    {'a':7,'b':2},
];

const withIndexes = myArray.map(
    (x, i) => ({index: i, value: x}));

withIndexes.sort(compareAll(
    (a, b) => -compareDefault(a.value.b, b.value.b),
    (a, b) => compareDefault(a.index, b.index),
));

const sorted = withIndexes.map(x => x.value);

console.log(sorted);