JavaScript 手撕大厂面试题数组扁平化以及增加版本 plus

前言

现在的前端面试手撕题是一个必要环节,有点时候八股回答的不错但是手撕题没写出来就会让面试官印象分大减,很可能就挂了...

概念

数组的扁平化 其实就是将一个多层嵌套的数组转换为只有一层的数组

比如: [1, [2, [3, [4, 5]]]] => [1,2,3,4,5,6]

题目

一、实现一个 flat() easy 难度

javascript 复制代码
function myFlat(arr) {
  let result = [];
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      result = result.concat(myFlat(arr[i]));
      // res = [...res, ...myFlat(arr[i])] 这样写也可以
    } else {
      result.push(arr[i])
    }
  }
  return result
}

二、用递归实现 medium 难度

javascript 复制代码
const flat = arr => {
  let res = []
  let rStack = [...arr]
  while (rStack.length) {
    let top = rStack.shift()
    if (Array.isArray(top)) {
      rStack.unshift(...top)
    } else {
      res.push(top)
    }
  }
  return res
}

三、控制扁平化的深度 medium 难度

depth 为展平的深度 比如 1 就是将整体深度减一

javascript 复制代码
const myFlat = (arr, depth) => {
  let result = []
  for (const element of arr) {
    if (Array.isArray(element) && depth > 0) {
      result = [...result, ...myFlat(element, depth - 1)]
    } else {
      result.push(element)
    }
  }
  return result
}

四、计算嵌套数组的深度 medium 难度
类似层序遍历!

javascript 复制代码
const getDepth = arr => {
  const queue = [...arr]
  let depth = 1
  while (queue.length > 0) {
    const curLen = queue.length
    for (let i = 0; i < curLen; i++) {
      const cur = queue.shift()
      if (Array.isArray(cur)) {
        queue.push(...cur)
      }
    }
    depth++
  }
  return depth - 1
}

五、递归控制扁平化的深度 hard 难度

javascript 复制代码
function flattenArrayWithDepth(arr, depth) {
  const flattenedArray = [];
  const queue = [{ array: arr, remainingDepth: depth }];
  while (queue.length > 0) {
    const { array, remainingDepth } = queue.shift();
    for (const item of array) {
      if (Array.isArray(item) && remainingDepth > 0) {
        queue.push({ array: item, remainingDepth: remainingDepth - 1 });
      } else {
        flattenedArray.push(item);
      }
    }
  }
  return flattenedArray;
}
相关推荐
星空露珠几秒前
迷你世界UGC3.0脚本Wiki对象模块管理接口 GameObject
开发语言·数据库·算法·游戏·lua
陈随易2 分钟前
MoonBit访谈:MoonBit开发moonclaw实现“养虾”自由
前端·后端·程序员
码界奇点3 分钟前
基于Java GUI和Access数据库的图书馆管理系统设计与实现
java·开发语言·数据库·毕业设计·源代码管理
Moshow郑锴8 分钟前
JAVA JDK26新特性分析 - 一个注重性能优化、生产就绪和前瞻性安全的版本
java·开发语言·jvm
汀沿河11 分钟前
3 LangChain 1.0 中间件(Middleware)- after_model、after_agent
前端·中间件·langchain
紫金修道12 分钟前
【OpenClaw】让openclaw根据需求创造自定义skill记录
前端·javascript·chrome
Jackey_Song_Odd15 分钟前
Part 1:Python语言核心 - 缩进与代码块
开发语言·python
周杰伦fans19 分钟前
Edge浏览器 about:blank 问题修复
前端·数据库·edge
嘉琪00120 分钟前
Day6 完整学习包(async/await)——2026 0318
前端·javascript·学习
SameX24 分钟前
我做了个本地优先的 iOS 足迹 App,上架后才发现:最难的根本不是地图,而是让轨迹活下来
前端