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

What's the right way to sort the child object by their property in a Map in Immutable.js

我有一张地图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();