对 JavaScript 数组进行分组
假设我们有一个如下 JavaSCript 数组 −
const data = [
{
"dataId": "1",
"tableName": "table1",
"column": "firstHeader",
"rows": [
"a","b","c"
]
},
{
"dataId": "2",
"tableName": "table1",
"column": "secondHeader",
"rows": [
"d","e","f",
]
}, {
"dataId": "3",
"tableName": "table2",
"column": "aNewFirstHeader",
"rows": [
1,2,3
]
}
];我们需要编写一个 JavaScript 函数,该函数位于其中一个数组中。该函数应该基于原始数组构建一个新的分组对象数组。
分组数组应将用于各个唯一“tableName”对象的的数据包含在自己的对象中。
因此,最终,输出应如下所示 −
const output = [
{
"tableName": "table1",
"column": ["firstHeader", "secondHeader"],
"rows": [["a","b","c"], ["d","e","f"]]
},
{
"tableName": "table2",
"column": ["aNewFirstHeader"],
"rows": [[1,2,3]]
}
];示例
const arr = [
{
"dataId": "1",
"tableName": "table1",
"column": "firstHeader",
"rows": [ "val","b","c" ]
},
{
"dataId": "2",
"tableName": "table1",
"column": "secondHeader",
"rows": [
"d","e","f",
]
},
{
"dataId": "3",
"tableName": "table2",
"column": "aNewFirstHeader",
"rows": [
1,2,3
]
}
];
const groupArray = (arr = []) => {
const res = arr.reduce((obj => (acc, val) => {
let item = obj.get(val.tableName);
if (!item) {
item = {
tableName: val.tableName, column: [], rows: []
}
obj.set(val.tableName, item); acc.push(item);
};
item.column.push(val.column); item.rows.push(val.rows);
return acc;
})(new Map), []);
return res;
};
console.log(JSON.stringify(groupArray(arr), undefined, 4));输出
控制台中输出的结果为 −
[
{
"tableName": "table1",
"column":
[
"firstHeader",
"secondHeader"
],
"rows": [
[
"val", "b", "c"
],
[
"d", "e", "f"
]
]
}, {
"tableName": "table2",
"column": [
"aNewFirstHeader"
],
"rows": [
[
1, 2, 3
]
]
}
]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP