2

I am trying to sort with two fields, say first name then last name. How do I chain Intl.Collator().compare so I don't have to do something silly like

const collator = new Intl.Collator()

const sorted = [...unsorted].sort( (a,b) => {
  const c0 = collator.compare(a.firstName, b.firstName)
  if (c0 === 0) {
    return collator.compare(a.lastName, b.lastName)
  }
  else {
    return c0;
  }
}

I am basically looking for an equivalent of Java's Comparator.thenComparing()

This is specifically strings and specifically the Intl.Collate() to handle accents so the techniques in Javascript sort array by two fields do not work well or equivalent to the implementation above.

Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265
  • closing as duplicate since the answer is relatively the same but MOD if you want to open it because it is sufficiently different feel free to do so. – Archimedes Trajano Jul 28 '21 at 21:26

1 Answers1

4

Buried deep in https://stackoverflow.com/a/46469791/242042 but I adapted it to

const sorted = [...unsorted]
  .sort( (a,b) => 
    collator.compare(a.firstName, b.firstName) ||
    collator.compare(a.lastName, b.lastName)
  );

relying on the fact that when equal the result is 0 and that translates to false which triggers the execution of the result after the ||

Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265