javascript - Chrome稳定排序功能

标签 javascript

我正在尝试获取 Chrome 的 Array.sort()功能要稳定。我知道还有其他库可以实现稳定排序,但我正在尝试获取 native 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}
]

最佳答案

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

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);

关于javascript - Chrome稳定排序功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47216537/

相关文章:

javascript - 为什么以下映射函数返回带逗号的字符串?

javascript - 从 String 中提取 HTML 标签并将其设为 "Use"

javascript - 如何根据类似的类获取容器内元素的索引?

javascript - 我该如何对这种对象进行排序?

javascript - 在滚动时折叠具有动态高度的标题

javascript - 通过另一个元素进行 jQuery 悬停检测?

javascript - wsapi 存储的过滤功能在 Rally SDK 中不起作用

php - jQueryUI 自动完成 : Returning data from multiple columns in a MySQL database and joining them

javascript - 尝试使用鼠标滚轮时垂直滚动条不起作用#FF,Chrome

javascript - 如何在 Chart.js 上检查图表类型