假设我们有一个由数字表示的数字数组,如下所示:
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' ] ]