four-eyes
four-eyes

Reputation: 12439

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?

Upvotes: 1

Views: 2524

Answers (2)

Anurag Singh Bisht
Anurag Singh Bisht

Reputation: 2753

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>

Upvotes: 1

31piy
31piy

Reputation: 23859

You can create a copy using Array#from and then sort that. This will not change the original array.

Also, Array#form can be used on ImmutableJS list, which will return the corresponding JS array.

let data = [{someKey: 1, date: 823748943}, {someKey: 2, date: 2389472938}, {someKey: 3, date: 81278734}];

console.log(Array.from(data).sort((a, b) => a.date - b.date));
console.log(data);

Upvotes: 0

Related Questions