前端八股整理(手写 02)|数组转树、数组扁平化、随机打乱一个数组

前端八股整理(手写 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));
相关推荐
Mh18 小时前
别再只会 `find` 了:Map 在前端业务里的真实用法
前端·javascript
陈随易19 小时前
FFmpeg 9.0 发布,代号 Lei,音视频处理再升级
前端·后端·程序员
爱丶狸19 小时前
Grafana_Zabbix_ImageRenderer_部署与前端操作手册
linux·前端·zabbix·grafana·kylin
用户059540174461 天前
把AI对话记忆存储测试从手工改成Playwright+pytest,覆盖率从20%提到96%,回归时间缩短90%
前端·css
kyriewen1 天前
别再这样写TypeScript了——Code Review中最常见的8个反模式
前端·javascript·typescript
名字还没想好☜1 天前
Next.js ‘use client‘ 到底加在哪:Server/Client Components 边界与常见报错
开发语言·前端·javascript·react·next.js
午安~婉1 天前
GitHub Token/ GitHub Stats统计显示图异常
前端·github·vercel·github token
码云之上1 天前
AI Agent 工程化总览篇:从 Prompt 到 Harness
前端·人工智能
2501_926978331 天前
以说明书 DNA 为模板——完整 AGI 的结构图景
前端·人工智能·经验分享·笔记·ai写作
IT_陈寒1 天前
Vite静态资源引用这个坑我踩得有点疼
前端·人工智能·后端