基于 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 ] ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP