前端八股整理(手写 02)|数组转树、数组扁平化、随机打乱一个数组(洗牌算法)
1.数组转树
扁平数组转成树形结构(tree data)
也就是将
javascript
const list = [
{ id: 1, name: '部门A', parentId: 0 },
{ id: 2, name: '部门B', parentId: 1 },
{ id: 3, name: '部门C', parentId: 1 },
{ id: 4, name: '部门D', parentId: 2 }
]
转化为
javascript
[
{
id: 1,
name: '部门A',
parentId: 0,
children: [
{
id: 2,
name: '部门B',
parentId: 1,
children: [
{
id: 4,
name: '部门D',
parentId: 2,
children: []
}
]
},
{
id: 3,
name: '部门C',
parentId: 1,
children: []
}
]
}
]
思路:
创建一个 map 对象和 result 数组,map 数组建立映射 id 和内容的新映射,但是新映射中多了一个字段 children数组.创建一个 result 数组,作为最终的结果
遍历数据,如果 parentId=0,表示它是最外层的树,把它放入数组中,其他的内容放在对应 parentId 对应的 children 数组中.
javascript
const list =[
{id:1,name:'部门 A',parentId:0},
{id:2,name:'部门 B',parentId:1},
{id:3,name:'部门 C',parentId:1},
{id:4,name:'部门 D',parentId:2}
];
function arrrytotree(list)
{
let map={};
let result=[];
for(const item of list)
{
map[item.id]={
...item,
children:[]
};
}
for(const item of list)
{
const node=map[item.id];
if(item.parentId===0) result.push(node);
else
{
map[item.parentId].children.push(node);
}
}
return result;
}
const result= arrrytotree(list);
console.log(JSON.stringify(result, null, 2));
2.数组扁平化-手动实现 flat()
数组扁平化到底是什么?
数组扁平化,就是把嵌套数组展开,变成层级更浅的数组,甚至变成一维数组。
[1, [2, 3], [4, [5, 6]]]
变为
[1, 2, 3, 4, 5, 6]
这就叫数组扁平化。
扁平化也分为扁平几层,如果是扁平一层的话:
[1, 2, 3, 4, [5, 6]]
扁平两层
[1, 2, 3, 4, 5, 6]
最简单的无限扁平化写法
javascript
function myFlat(arr)
{
const result =[];
for(let item of arr)
{
if(Array.isArray(item)) result.push(...myFlat(item));
else result.push(item);
}
return result;
}
如果要控制扁平的层数
javascript
function myFlat(arr,depth=1)
{
const result =[];
for(let item of arr)
{
if(Array.isArray(item)&&depth>0) result.push(...myFlat(item,depth-1));
else result.push(item);
}
return result;
}
3.如何随机打乱一个数组(math.random)
Fisher-Yates 洗牌算法:从数组最后一个元素开始,随机选一个 [0, i] 范围内的元素,和当前位置交换,然后继续向前处理。
每一轮确定一个位置
javascript
const arr=[3,1,9,23,55,98];
function shuffle(arr)
{
const result=[...arr];
for(let i=arr.length-1;i>=0;i--)
{
const j= Math.floor(Math.random()*(i+1));
[result[i],result[j]]=[result[j],result[i]]
}
return result;
}
console.log(shuffle(arr));