我想根据某种布尔条件对列表中的元素进行排序:如果为true,则将这些元素放在后面。因此,我将sort
与compareFunction
一起使用,如下所示:
myArray.sort(elem => booleanCondition(elem) ? 1 : -1);
但是,对于elem
给出值-1的testArray = ["first", "second", "third", "fourth"]
console.log(testArray.sort(e => 1))
console.log(testArray.sort(e => 1))
console.log(testArray.sort(e => 1))
console.log(testArray.sort(e => 1))
> Array ["first", "second", "third", "fourth"]
> Array ["first", "second", "third", "fourth"]
> Array ["first", "second", "third", "fourth"]
> Array ["first", "second", "third", "fourth"]
,顺序将在重复调用时发生变化。
我在这里尝试了一个简单的测试:
console.log(testArray.sort(e => -1))
console.log(testArray.sort(e => -1))
console.log(testArray.sort(e => -1))
console.log(testArray.sort(e => -1))
> Array ["fourth", "third", "second", "first"]
> Array ["first", "second", "third", "fourth"]
> Array ["fourth", "third", "second", "first"]
> Array ["first", "second", "third", "fourth"]
但是:
sort
我希望顺序保持一致-类似于1排序的工作方式。它不必保留原始顺序,只需保持一致即可(因此它不会一直在我的前端:P上跳来跳去)
问题:将compareFunction
与返回-1的{{1}}一起使用时,如何为元素赋予一致的顺序?