Search code examples
javascriptunix-timestampimmutable.js

Sort List by date Immutable JS


I have a Immutable JS List with Objects. In each Object there is a key date with a UNIX timestamp

[{someKey: 1, date: 823748943}, {someKey: 2, date: 2389472938}, {someKey: 3, date: 81278734}]

How would I sort the List by date?


Solution

  • Only a select few methods can be used in withMutations including set, push and pop. These methods can be applied directly against a persistent data-structure where other methods like map, filter, sort, and splice will always return new immutable data-structures and never mutate a mutable collection.

    var list = Immutable.List.of({someKey: 1, date: 823748943}, {someKey: 2, date: 2389472938}, {someKey: 3, date: 81278734});
    
    var sortedList = list.sort(function(lhs, rhs) {
      return lhs.date > rhs.date;
    });
    
    console.log(list);
    console.log(sortedList);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.min.js"></script>