数组篇2
1、树形结构构建函数
// 不需要传入顶级节点
function buildTree(data) {
let map = {};
data.forEach((node) => {
node.children = [];
map[node.id] = node;
});
let roots = [];
data.forEach((node) => {
if (map[node.parentId]) {
map[node.parentId].children.push(node);
} else {
roots.push(node);
}
});
return roots;
}
2、数组分组函数
Array.prototype.groupBy = function(fn) {
return this.reduce((acc, item) => {
const key = fn(item);
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(item);
return acc;
}, {});
};
const array = [{"id": "1"}, {"id": "1"}, {"id": "2"}];
const fn = function(item) {
return item.id;
};
const grouped = array.groupBy(fn);
console.log(grouped);