按 JavaScript 中的嵌套数组进行分组
假设我们有如下一个值数组 −
const arr = [
{
value1:[1,2],
value2:[{type:'A'}, {type:'B'}]
},
{
value1:[3,5],
value2:[{type:'B'}, {type:'B'}]
}
];我们需要编写一个 JavaScript 函数,该函数采用一个这样的数组。然后,我们的函数应准备一个数组,其中数据根据对象的“类型”属性进行分组。
因此,对于上面的数组,输出应如下所示 −
const output = [
{type:'A', value: [1,2]},
{type:'B', value: [3,5]}
];例子
其代码将为 −
const arr = [
{
value1:[1,2],
value2:[{type:'A'}, {type:'B'}]
},
{
value1:[3,5],
value2:[{type:'B'}, {type:'B'}]
}
];
const groupValues = (arr = []) => {
const res = [];
arr.forEach((el, ind) => {
const thisObj = this;
el.value2.forEach(element => {
if (!thisObj[element.type]) {
thisObj[element.type] = {
type: element.type,
value: []
}
res.push(thisObj[element.type]);
};
if (!thisObj[ind + '|' + element.type]) {
thisObj[element.type].value =
thisObj[element.type].value.concat(el.value1);
thisObj[ind + '|' + element.type] = true;
};
});
}, {})
return res;
};
console.log(groupValues(arr));输出
并且控制台中的输出将为 −
[
{ type: 'A', value: [ 1, 2 ] },
{ type: 'B', value: [ 1, 2, 3, 5 ] }
]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP