在 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' ]
]

更新时间:2020-10-12

249 次浏览

开启您的职业生涯

完成课程认证

开始学习
广告