如何根据对象的字母数字名称值正确对对象数组进行排序?
我试图按名称字段对对象数组进行排序,但顺序错误。
我得到的顺序是 [1, 10, 11, 2, 20, 21, 3]
而不是 [1, 2, 3, .... 10, 11, 20, 21]
它正在排序,但将 10 放在前面2
这是我当前使用的代码。
const arr = [
{
"name": "Action 10",
"color": "transparent",
"type": "components"
},
{
"name": "Action 11",
"color": "transparent",
"type": "components"
},
{
"name": "Action 2",
"color": "transparent",
"type": "components"
},
{
"name": "Action 20",
"color": "transparent",
"type": "components"
},
{
"name": "Action 21",
"color": "transparent",
"type": "components"
},
{
"name": "Action 3",
"color": "transparent",
"type": "components"
},
{
"name": "Action 4",
"color": "transparent",
"type": "components"
},
{
"name": "Action 5",
"color": "transparent",
"type": "components"
},
{
"name": "Action 6",
"color": "transparent",
"type": "components"
},
{
"name": "Action 1",
"color": "transparent",
"type": "components"
}
]
function sorter(a, b) {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
}
console.log(arr.sort(sorter));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
人们可以给出
数字
排序选项 href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare" rel="nofollow noreferrer">
String.prototype.localeCompare
尝试一下...One could give the
numeric
sorting option ofString.prototype.localeCompare
a try ...顺序是正确的。字符串“Action 10”将大于
Action 1
且小于Action 2
,因为字符串比较是逐个字符进行的。字符串比较的算法可以在这里找到: https://262.ecma- International.org/5.1/#sec-11.8.5
或者,作为 JavaScript 函数,表达式
str1 < str2
的计算就像调用此函数一样(并不是任何理智的人都会实现规范中描述的算法):如果您想根据语义含义对事物进行排序 of
name
,您需要将字符串划分为非数字段和数字段的列表,将数字位转换为数字,然后按从左到右的顺序比较这些段向右。The ordering is correct. The string "Action 10" collates greater than
Action 1
and less thanAction 2
, because string comparison is done on a character by character basis.The algorithm for string comparision is found here: https://262.ecma-international.org/5.1/#sec-11.8.5
Or, as a javascript function, the expression
str1 < str2
is evaluated as if this function were invoked (not that anybody sane would implement the algorithm as described in the spec):If you want to order things according to the semantic meaning of
name
, you'll need to partition the string into a list of its non-numeric and numeric segments, convert the numeric bits into numbers, and then compare the segments in order from left to right.您可以使用正则表达式:
DEMO
You can use regular expressions:
DEMO