3

Please check this fiddle example

How can I sort an orderedMap object by the keys sequence in a descending order? I know there is a sortBy method but the document doesn't give a clearer example.

Here's my original object:

var props = {
  "item": {
    "A": {
      "sequence": 5
    },
    "B": {
      "sequence": null
    },
    "C":{
      "sequence": 2
    }
  }
}

I'd like the result to be like:

var props = {
  "item": {
    "A": {
      "sequence": 5
    },
    "C":{
      "sequence": 2
    },
    "B": {
      "sequence": null
    }
  }
}

Example Code:

var data = Immutable.fromJS(props,(key, value)=>{
     var isIndexed = Immutable.Iterable.isIndexed(value);
     return isIndexed ? value.toList() :value.toOrderedMap();
});

var sorted = data.get('item').sortBy((item) => item.get('sequence'));

console.log(sorted.toJS())
RedGiant
  • 4,444
  • 11
  • 59
  • 146
  • [Javascript Objects are unordered by definition](http://stackoverflow.com/a/1069705/2260614), after `toJS()` the sort order is in a few cases maintained but not always. – Bhavik Sep 07 '16 at 18:08

1 Answers1

11

The function you are providing to sortBy() is comparator and it needs to return a Number. By adding a minus in front of the item.get('sequence') or following the result with reverse() you will reverse the sort, getting you the output that you want.

Here's an example:

var sorted = data.get('item').sortBy((item) => -item.get('sequence'));
// or var sorted = data.get('item').sortBy((item) => item.get('sequence')).reverse();
// you can now use .map() to go through your OrderedMap which has been
// sortbed by the sequence property and would look like your desired output

Note that you are working with an OrderedMap and that simply calling sorted.toJS() would return a regular JS object where the keys are, obviously, not sorted.

// If you need to iterate through the map and return some 
// plain JS you can do something like:
sorted.map(x => x.get('sequence')).toJS()
// => Object {A: 5, C: 2, B: null}
VanDanic
  • 432
  • 5
  • 12