今天去笔试的时候遇到了一题,是关于数组扁平化的,但是我是不知道的,只想出了一个简单的逻辑,没实现出来,后来经过朋友讲解之后才知道是数组扁平化,我回家赶紧查了相关的资料,并且把他做出来
题目是这样的:
[
{ pid: 0, id: 1, name: "中国" },
{ pid: 1, id: 2, name: "广东" },
{ pid: 2, id: 3, name: "深圳" },
{ pid: 3, id: 6, name: "福田" },
{ pid: 1, id: 4, name: "香港" },
{ pid: 4, id: 5, name: "九龙" },
];
有个这样的数据,我们需要处理成
[
{ pid: 0, id: 1, name: "中国",children:[
{ pid: 1, id: 2, name: "广东",children: [
{ pid: 2, id: 3, name: "深圳",children: [
{ pid: 3, id: 6, name: "福田" },
] },
] },
{ pid: 1, id: 4, name: "香港",children: [
{ pid: 4, id: 5, name: "九龙" },
] },
] },
];
我们可以从这里看到一个规律:
pid
等于id
,那么这个相等的id
对象是pid
对象的子元素放上我的具体实现代码:
<script>
let arr = [
{ pid: 0, id: 1, name: "中国" },
{ pid: 1, id: 2, name: "广东" },
{ pid: 2, id: 3, name: "深圳" },
{ pid: 3, id: 6, name: "福田" },
{ pid: 1, id: 4, name: "香港" },
{ pid: 4, id: 5, name: "九龙" },
];
// 数组扁平化
// 使用reduce作为高阶函数,reduce可以传入一个函数做为参数
// total 必需。初始值, 或者计算结束后的返回值。
// currentValue 必需。当前元素
// index 可选。当前元素的索引
// arr 可选。当前元素所属的数组对象。
let newArr = [];
function rank(total, currentValue, index, array) {
console.log(total, currentValue, index);
if (total) {
total.pid === 0 && newArr.push(total);
total.chlidren = [];
}
array.forEach((item) => {
if (total.id === item.pid) {
total.chlidren.push(item);
}
});
return currentValue;
}
arr.reduce(rank);
console.log(newArr);
</script>
总的来说面试的时候没有回答上来,事后学习了新知识也不亏