javascript - 使用字符串字母顺序的jQuery排序数组
问题描述
我有一个数组,我想使用名称对象按字母顺序对数组进行排序。
目前,它排序正确,但有一个小问题。
https://jsfiddle.net/b3hv75u8/1/
var arry = [{
'name': '2.1 Foo',
'children': [{
'name': '2.1.1 Foo ',
},
{
'name': '2.1.3 Foo ',
},
{
'name': '2.1.10 Foo ',
},
{
'name': '2.1.2 Foo ',
},
],
},
{
'name': '1.1 Foo',
'children': [{
'name': '1.1.2 Foo ',
},
],
},
];
function SortByName(a, b){
if(a.children){
a.children = a.children.sort(SortByName)
}
if(b.children){
b.children = b.children.sort(SortByName)
}
var aName = a.name.toLowerCase();
var bName = b.name.toLowerCase();
return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}
$(document).ready(function() {
var sorted_array = arry.sort(SortByName)
console.log(sorted_array)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
对于上面的代码输出是
[
{
"name": "1.1 Foo",
"children": [
{
"name": "1.1.2 Foo "
}
]
},
{
"name": "2.1 Foo",
"children": [
{
"name": "2.1.1 Foo "
},
{
"name": "2.1.10 Foo " // this is wrong
},
{
"name": "2.1.2 Foo "
},
{
"name": "2.1.3 Foo "
}
]
}
]
预期操作
[
{
"name": "1.1 Foo",
"children": [
{
"name": "1.1.2 Foo "
}
]
},
{
"name": "2.1 Foo",
"children": [
{
"name": "2.1.1 Foo "
},
{
"name": "2.1.2 Foo "
},
{
"name": "2.1.3 Foo "
},
{
"name": "2.1.10 Foo "
}
]
}
]
解决方案
在比较之前,您需要使用正则表达式来消除点。
var arry = [
{
'name': '2.1 Foo',
'children': [{
'name': '2.1.1 Foo ',
},
{
'name': '2.1.3 Foo ',
},
{
'name': '2.1.10 Foo ',
},
{
'name': '2.1.2 Foo ',
},
],
},
{
'name': '1.1 Foo',
'children': [{
'name': '1.1.2 Foo ',
},
],
},
];
function SortByName(a, b){
if(a.children){
a.children = a.children.sort(SortByName)
}
if(b.children){
b.children = b.children.sort(SortByName)
}
var aName = parseInt( a.name.toLowerCase().replace(/\./g, "") );
var bName = parseInt( b.name.toLowerCase().replace(/\./g, "") );
return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}
$(document).ready(function() {
var sorted_array = arry.sort(SortByName)
console.log(sorted_array)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
推荐阅读
- excel - 从网页中读取阿拉伯字符
- php - PHP MySQL AngularJS 在用户停止从表行中输入后提取一个单词
- c# - 检查多维矩阵的最后一行是否包含元音
- android - 在不打开菜单的情况下更改页面
- python - Django session keyerror,如何保存从 Angular 到 django 到 http 跨域请求之间的 django 会话状态
- assembly - 基于寄存器值的汇编调用中断
- python - 姜戈;将值从下拉列表传递到主页
- python - 是否可以计算 LDA 语料库中每个文档的文档相似度?
- python - PyCharm:如何推断在运行时创建的对象类型
- python - 如果它们存在于 Pandas 中,则聚合对称对