前端八股整理(手写 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));
相关推荐
深蓝AI4 分钟前
编码 Agent 的界面味靠提示词压不住:Impeccable 用无模型规则拦同一套模板
前端·程序员
January12071 小时前
【AI方法笔记】2026-11-02:模型流式吐 JSON 时,前端会遇到四种崩法
前端·人工智能·笔记·json
asdzx671 小时前
C# 操作 PDF 元数据:从属性写入到字段提取的完整流程
前端·pdf·c#
吹什么轩2 小时前
constexpr 完全指南:从 const 的两种含义,到编译期计算的四次演进
java·前端·javascript
Bruce_Liuxiaowei2 小时前
前端校验登录态,等于没校验——一次应急广播终端高危漏洞的发现与报送
运维·前端·安全
Meta Luo2 小时前
AI 时代,Web 自动化测试该怎么做?
前端·人工智能·playwright 替代工具·无代码自动化测试工具·低代码 ui 自动化测试·web 回归测试工具
去伪存真2 小时前
AI Agent 性能评估指标与自动化测试落地方案
前端·agent
MaAidan3 小时前
用 Agent 排查线上问题:SLS 日志分析 + DB/Redis 数据验证,一条链路搞清楚
前端·bootstrap·html
墨林陌3 小时前
AI 热点日报(2026-11-03):美团发布 1.6 万亿参数国产大模型,四大厂商共推 AI 训练退出标准
前端
Moment3 小时前
DeepSeek 发布新模型,直接把 Agent 联网搜索的门槛打下来了!
前端·后端