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

Typescript sort by string property value

I have a list of object I want to sort by string property. Property values are D1, D2 … D10 … DXX. It’s always D with number. When I use this code to sort the array by property, it doesn’t sort it the way I expect to – ascending. I am using this piece of code to sort array.

this.list = v.sort((a, b) => a.property.localeCompare(b.property));

Result are sorted like this:

Index Property value
0 D10
1 D11
2 D3
3 D5

How do I achieve sorting it the right way? Example:

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

Index Property value
0 D3
1 D5
2 D10
3 D11

>Solution :

Your properties are strings, therefore they are sorted lexicographically

What I believe you want is to sort by the "numeric component of your string value". You therefore have to extract the number from the string to perform a numeric sort

extractNumber(stringValue: string) {
  // Assumes all strings have a single character 'D' prepended
  return Number(stringValue.substring(1))
}

this.list = v.sort((a, b) => extractNumber(a.property) - extractNumber(b.property));
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