根据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 ] ]
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便