gpt4 book ai didi

javascript - 在 Immutable.js 的 Map 中按属性对子对象进行排序的正确方法是什么

转载 作者:行者123 更新时间:2023-11-28 05:32:55 25 4
gpt4 key购买 nike

我有一张 map m:

var m = Immutable.fromJS({
first: {a: 6, b: 3},
second: {a: 3, b: 6},
third: {a: 2, b: 4}
})

我想获取 m 中的子对象,按其属性 b 排序,如下所示:

[
{a: 6, b: 3},
{a: 2, b: 4},
{a: 3, b: 6}
]

我尝试过以下方法:

m.valueSeq().sort(function(a, b) {
return a.get('b') > b.get('b')
}).toJS()

它在 Chrome 和 Node.js 中运行良好,但在 OS X 中的 Safari v8.0 中,结果是

[
{a: 6, b: 3},
{a: 3, b: 6},
{a: 2, b: 4}
]

它根本没有排序!这在我的 React/Redux 应用程序中造成了一些错误。这是怎么回事?正确的排序方法是什么?谢谢!

最佳答案

您的自定义比较函数需要返回 1、-1 或 0 才能正确对项目进行排序。

m.valueSeq().sort(function(a, b) {
if (a.get('b') > b.get('b')) return 1;
if (a.get('b') < b.get('b')) return -1;
else return 0;
}).toJS();

关于javascript - 在 Immutable.js 的 Map 中按属性对子对象进行排序的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39558334/

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