gpt4 book ai didi

javascript - 匹配相同值的十进制数以插入数组

转载 作者:行者123 更新时间:2023-11-30 15:04:20 25 4
gpt4 key购买 nike

我在数组中有一个 Srings

var QNo = ["1.1","1.2","1.3","2.1","2.2","3.1","3.2","3.3","4.1","4.2"];

需要像这样更改具有匹配小数的对象数组中的QNo

var result = [["1.1","1.2","1.3"],["2.1","2.2"],["3.1","3.2","3.3"],["4.1","4.2"]];

我试过这种代码

for (var j = 0; j < QNo.length ; j++) {
if ( QNo[j].match(/.*(?=\.)/g) ) {
result.push(QNo[j]);
}
}

比赛结束后,我不知道将小数值作为对象推送

最佳答案

您可以取出拆分值的左侧部分并检查最后一个值是否在同一组中——然后将该值推送到组中。如果没有,则建立一个新组。

var qNo = ["1.1", "1.2", "1.3", "2.1", "2.2", "3.1", "3.2", "3.3", "4.1", "4.2"],
result = qNo.reduce(function (r, a, i, aa) {
function left(a) { return (a || '').split('.')[0]; }
if (left(a) === left(aa[i - 1])) {
r[r.length - 1].push(a);
} else {
r.push([a]);
}
return r;
}, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

对于未排序的值,您可以使用哈希表并稍后对结果进行排序。

var qNo = ["1.1", "3.1", "1.2", "1.3", "2.1", "3.2", "3.3", "4.1", "2.2", "4.2"],
hash = Object.create(null),
result = qNo.reduce(function (r, a, i, aa) {
function left(a) { return (a || '').split('.')[0]; }
var key = left(a);
if (!hash[key]) {
hash[key] = [];
r.push(hash[key]);
}
hash[key].push(a);
return r;
}, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 匹配相同值的十进制数以插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46014987/

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