根据JavaScript中的元素对数组进行分组
假设我们有一个数字数组,像这样-
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 ] ]