根据第一个值分割数组-JavaScript

2023年11月22日08:59:31

假设我们有一个数字数组,像这样-

const arr = [[1, 45], [1, 34], [1, 49], [2, 34], [4, 78], [2, 67], [4, 65]];

每个子数组必须严格包含两个元素。我们需要编写一个构造新数组的函数,在该函数中,具有相似第一值的子数组的所有第二个元素都被分组在一起。

因此,对于上面的数组,输出应类似于-

const output = [
   [45, 34, 49],
   [34, 67],
   [78, 65]
];

我们可以利用Array.prototype.reduce()方法来帮助Map()构建所需的数组。

示例

以下是代码-

const arr = [[1, 45], [1, 34], [1, 49], [2, 34], [4, 78], [2, 67], [4, 65]];
const constructSimilarArray = (arr = []) => {
   const creds = arr.reduce((acc, val) => {
      const { map, res } = acc;
      if(!map.has(val[0])){
         map.set(val[0], res.push([val[1]]) - 1);
      }else{
         res[map.get(val[0])].push(val[1]);
      };
      return { map, res };
   }, {
      map: new Map(),
      res: []
   });
   return creds.res;
};
console.log(constructSimilarArray(arr));

输出结果

这将在控制台中产生以下输出-

[ [ 45, 34, 49 ], [ 34, 67 ], [ 78, 65 ] ]

  • 更新时间:2023年11月22日08:59:31 ,共 818 字。