How can I sort an ImmutableJS List object on multiple keys?

I have a list of job history objects that have start and end date fields. I need to sort start and then end . If the dates overlap between work history objects when I use the back-to-back sort() functions, the order may be disabled. I need a way to sort the ImmutableJS list by multiple keys, where the second sort key is only processed when the values ​​of the first key are equal. I would suggest that ImmutableJS would have an easier way to handle this type of sort. Here is what I came up with, but it seems awful to me (using momentJS to compare dates):

  const sortedWorkHistory = workHistory.sort((b, a) => { const aTo = moment(a.get('to') === null ? undefined : a.get('to')); const bTo = moment(b.get('to') === null ? undefined : b.get('to')); if (aTo.isBefore(bTo)) { return -1; } if (bTo.isBefore(aTo)) { return 1; } return 0; }) .sort((b, a) => { const aTo = moment(a.get('to') === null ? undefined : a.get('to')); const bTo = moment(b.get('to') === null ? undefined : b.get('to')); if (aTo === bTo) { const aFrom = moment(a.get('from')); const bFrom = moment(b.get('from')); if (aFrom.isBefore(bFrom)) { return -1; } if (bFrom.isBefore(aFrom)) { return 1; } return 0; } }); 
0
source share
2 answers

aTo === bTo will never be equal as you define it. You are comparing links to objects that are always different. You will need to use the .isSame method. You can verify this by trying this:

 const a = moment().startOf('day'); const b = moment().startOf('day'); console.log(a === b); // false console.log(a.isSame(b)); // true 

Here is what I would do:

 // Helper function to create moments function parseMoment(date) { return moment(date === null ? undefined : date); } const sortedWorkHistory = workHistory .sort((a, b) => parseMoment(a.get('to')).diff(parseMoment(b.get('to')))) .sort((a, b) => { if(parseMoment(a.get('to')).isSame(parseMoment(b.get('to')))) { return parseMoment(a.get('from')).diff(parseMoment(b.get('from'))) } return 0; }); 
+1
source

You can put this in one comparison function, for example:

 const sortedWorkHistory = workHistory.sort((b, a) => { const aTo = moment(a.get('to')); const bTo = moment(b.get('to')); const aFrom = moment(a.get('from')); const bFrom = moment(b.get('from')); if (aTo.isBefore(bTo)) { return -1; } else if (bTo.isBefore(aTo)) { return 1; } else if (aFrom.isBefore(bFrom)) { return -1; } else if (bFrom.isBefore(aFrom)) { return 1; } return 0; }); 

Or maybe even

 const sortedWorkHistory = workHistory.sort((b, a) => { // aTo = ... if (aTo.isSame(bTo)) { return aFrom.diff(bFrom); } return aTo.diff(bTo); }); 
+2
source

All Articles