fhgsm123 fhgsm123 - 1 year ago 69
Javascript Question

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

I have an Map


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

I want to get the child objects in
sorted by their property
, like this:

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

I have tried below:

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

It works well in Chrome and node.js, but in Safari v8.0 in OS X, the result is

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

It did not sort at all! This made some bugs in my React/Redux app. What's the matter of it? And what is the right way to sort it? Thanks!

Answer Source

Your custom compare function requires the returning of 1, -1 or 0 in order to sort the items correctly.

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download