我有一个JSON,格式如下:
account = [
{"name":"Los Angeles", "country":"USA"},
{"name":"Boston", "country":"USA"},
{"name":"", "country":"USA"},
{"name":"Chicago", "country":"USA"}
]
Run Code Online (Sandbox Code Playgroud)
我试图按字母顺序将AZ BY NAME排序为空名称值.
我试过这个,但是,这首先用空值对AZ进行排序.
account.sort( function( a, b ) {
return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
});
Run Code Online (Sandbox Code Playgroud)
account.sort( function( a, b ) {
if(a.name === "") {
return 1;
} else if(b.name === "") {
return -1;
} else {
return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
}
});
Run Code Online (Sandbox Code Playgroud)
在字符串的情况下,空字符串被认为是最小值,因此被排序为数组中的第一个元素.
但是,我们需要根据我们的要求更改默认行为,因此我们必须为其添加额外的逻辑.
现在在排序中,当我们返回-1时,表示订单很好并且符合要求.当我们返回1时,表示顺序相反,需要交换,当返回0时,两个对象/值都相同,不需要任何操作.
现在,在我们的例子中,我们需要将空字符串移动到最后一个.因此,如果第一个对象/值是空字符串,则交换它并将其向右移动到数组中.当第二个对象/值为空字符串时,不需要任何操作,因为它需要最后.
因此,这就是事情的运作方式.
您需要额外的子句来测试空字符串。
account = [{
"name": "Los Angeles",
"country": "USA"
}, {
"name": "Boston",
"country": "USA"
}, {
"name": "",
"country": "USA"
}, {
"name": "Chicago",
"country": "USA"
}]
account.sort(function(a, b) {
if (b.name.length == 0) {
return -1;
}
if (a.name.length == 0) {
return 1;
}
return a.city.localeCompare(b.city);
});
console.log(account)Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1379 次 |
| 最近记录: |