英文:
Typescript sort by string property value
问题
我有一个对象列表,我想按字符串属性进行排序。属性值是D1, D2 ... D10 ... DXX。它始终是D后面跟着数字。当我使用以下代码按属性排序数组时,它没有按我期望的方式升序排序。我正在使用以下代码来对数组进行排序。
this.list = v.sort((a, b) => a.property.localeCompare(b.property));
结果按如下方式排序:
索引 | 属性值 |
---|---|
0 | D10 |
1 | D11 |
2 | D3 |
3 | D5 |
... | ... |
我如何实现正确的排序?示例:
索引 | 属性值 |
---|---|
0 | D3 |
1 | D5 |
2 | D10 |
3 | D11 |
... | ... |
英文:
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 |
... | ... |
答案1
得分: 2
您的属性是字符串,因此它们按字典顺序排序。
我认为您想要按字符串值的"数值组件"进行排序。因此,您需要从字符串中提取数字以执行数值排序。
extractNumber(stringValue: string) {
// 假定所有字符串都以单个字符 'D' 为前缀
return Number(stringValue.slice(1))
}
this.list = v.sort((a, b) => extractNumber(a.property) - extractNumber(b.property));
英文:
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.slice(1))
}
this.list = v.sort((a, b) => extractNumber(a.property) - extractNumber(b.property));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论