我知道如何按数字或字母排序,但不确定如何同时进行。
sessionStorage.cart
==> "[
{"id":1, "number":1, "other_attributes":"other_values"},
{"id":2, "number":2, "other_attributes":"other_values"},
{"id":"processing", "other_attributes":"other_values"},
{"id":2, "number":1, "other_attributes":"other_values"},
{"id":"deposit", "other_attributes":"other_values"}
]"
我想按 id
对购物车进行排序,适用以下条件:
- 首先显示
id
为整数的所有项目 - 然后显示所有
id
为字符串的项目 - 其中
id
为整数,如果多个item具有相同的整数,则按number
排序 - 其中
id
为字符串,按字母顺序排序
上面例子的最终结果应该是(JSON解析后,设置回sessionStorage
)
==> "[
{"id":1, "number":1, "other_attributes":"other_values"},
{"id":2, "number":1, "other_attributes":"other_values"},
{"id":2, "number":2, "other_attributes":"other_values"},
{"id":"deposit", "other_attributes":"other_values"},
{"id":"processing", "other_attributes":"other_values"},
]"
最佳答案
您可以使用 sort()
具有自定义排序功能
var arr = [{
"id": 1,
"number": 1,
"other_attributes": "other_values"
}, {
"id": 2,
"number": 2,
"other_attributes": "other_values"
}, {
"id": "processing",
"other_attributes": "other_values"
}, {
"id": 2,
"number": 1,
"other_attributes": "other_values"
}, {
"id": "deposit",
"other_attributes": "other_values"
}];
arr = arr.sort(function(a, b) {
// check both id's are number
if (typeof a.id == 'number' && typeof b.id == 'number') {
// check both are equal
if (a.id == b.id)
// if equal sort based on `number`
return a.numer - b.number
// else sort based on id
return a.id - b.id
// check first one is number
} else if (typeof a.id == 'number')
// since number have higher sort order return -1
return -1;
// check second one is number
else if (typeof b.id == 'number')
// since string have lower sort order return 1
return 1;
// in case both are string
else {
// return based on string comaprison
if (a.id > b.id)
return 1;
else if (a.id < b.id)
return -1
return 0;
}
});
document.write('<pre>' + JSON.stringify(arr, null, 3) + '</pre>');
关于javascript - 首先按数字中的给定属性对对象数组进行排序,然后是字母(数字具有子排序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36231920/