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:

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));

Leave a Reply