gpt4 book ai didi

Javascript 用数字对对象字符串进行排序

转载 作者:行者123 更新时间:2023-12-02 19:27:51 25 4
gpt4 key购买 nike

我在 javascript 中有以下 JSON 对象:

var stuff = [{
"id": "20",
"serial": "0/0/19:46,0/0/149:63"
}, {
"id": "8",
"serial": "0/0/151:215,0/0/151:233"
}, {
"id": "54",
"serial": "0/0/151:26,0/0/151:37"
}, {
"id": "22",
"serial": "0/0/155:29,0/0/155:36"
}, {
"id": "4",
"serial": "0/0/151:48,0/0/151:152"
}];

我想知道如何通过“serial”字段对对象进行排序,使其像这样(考虑到序列字符串中整数的值):

var stuff = [{
"id": "20",
"serial": "0/0/19:46,0/0/149:63"
}, {
"id": "54",
"serial": "0/0/151:26,0/0/151:37"
}, {
"id": "4",
"serial": "0/0/151:48,0/0/151:152"
}, {
"id": "8",
"serial": "0/0/151:215,0/0/151:233"
}, {
"id": "22",
"serial": "0/0/155:29,0/0/155:36"
}];

提前致谢。

最佳答案

这将为您完成:

var normalizer = /[:\/]/g;

function serialCompare(a, b) {
var alist = a.serial.replace(normalizer, ',').split(','),
blist = b.serial.replace(normalizer, ',').split(','),
i = 0, l = alist.length;
while (alist[i] === blist[i] && i < l) {
i += 1;
};
return (parseInt(alist[i], 10) - parseInt(blist[i], 10));
}

sortedstuff = stuff.sort(serialCompare);
// returns array sorted as you asked

See it in a fiddle .

如果您要经常排序,或者列表很长,您应该考虑创建存储在对象中的序列值的“规范化”版本。它可以是在serialCompare函数内部计算的数组,也可以是用前导零填充到相同长度的文本数字部分。

关于Javascript 用数字对对象字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11835976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com