在JavaScript中以相似数字开头的字符串分组
假设我们有一个由数字表示的数字数组,如下所示:
const arr = ["1.1","1.2","1.3","2.1","2.2","3.1","3.2","3.3","4.1","4.2"];
我们需要编写一个JavaScript函数,该函数接受一个这样的数组并将所有以相同数字开头的字符串分组到一个公共子数组中。
因此,我们函数的输出应类似于-
const output = [["1.1","1.2","1.3"],["2.1","2.2"],["3.1","3.2","3.3"],["4.1","4.2"]];
示例
为此的代码将是-
const arr = ["1.1","1.2","1.3","2.1","2.2","3.1","3.2","3.3","4.1","4.2"];
const groupSimilarStarters = arr => {
let res = [];
res = arr.reduce((acc, val, ind) => {
const firstChar = el => {
return (el || '').split('.')[0];
}
if(firstChar(val) === firstChar(arr[ind - 1])){
acc[acc.length - 1].push(val);
}else{
acc.push([val]);
};
return acc;
}, []);
return res;
}
console.log(groupSimilarStarters(arr));输出结果
控制台中的输出-
[ [ '1.1', '1.2', '1.3' ], [ '2.1', '2.2' ], [ '3.1', '3.2', '3.3' ], [ '4.1', '4.2' ] ]
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短