Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting Array by two properties in JavaScript

I am attempting to use .sort() to sort golf groups by their starting hole. I need the groups to be listed in the following order. 1A, 1B, 2A, 2B so on and so forth.

Currently, this is how I am sorting the data:

                        <% groups = groups.sort((a, b) => (a.position > b.position && a.letter > b.letter) ? 1 : -1)%>

Please ignore the abnormal HTML tags, this is being implemented in an e.js template

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Currently,the groups are displaying like this:
Preview

This is far from the order I need and if anybody has any input as to how to help with this it would be greatly appreciated!

Note:

The "position" property is the number (the 1 in the 1A)
The "letter" property is the letter (the A in the 1A)

The array in question (as logged in console)
Array

>Solution :

You’ll need to perform the comparisons separately – first compare the numbers and return appropriately if they’re different. Otherwise, if the numbers are the same, return the difference between the members with .localeCompare, which checks whether a character comes before another or not.

const groups = [
  { position: 1, letter: 'B' },
  { position: 2, letter: 'B' },
  { position: 1, letter: 'A' },
  { position: 2, letter: 'B' },
  { position: 2, letter: 'A' },
  { position: 1, letter: 'B' },
];
groups.sort((a, b) =>
  (a.position - b.position) ||
  a.letter.localeCompare(b.letter)
);
console.log(groups.map(group => group.position + group.letter));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading