gpt4 book ai didi

javascript - Chrome稳定排序功能

转载 作者:行者123 更新时间:2023-12-01 02:46:39 25 4
gpt4 key购买 nike

我正在尝试获取 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com