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;
}
相关推荐
天若有情6734 小时前
打破思维定式!C++参数设计新范式:让结构体替代传统参数列表
java·开发语言·c++
不务正业的前端学徒4 小时前
手写简单的call bind apply
前端
斯特凡今天也很帅4 小时前
python测试SFTP连通性
开发语言·python·ftp
jump_jump4 小时前
Ripple:一个现代的响应式 UI 框架
前端·javascript·前端框架
sunywz4 小时前
【JVM】(4)JVM对象创建与内存分配机制深度剖析
开发语言·jvm·python
亲爱的非洲野猪4 小时前
从ReentrantLock到AQS:深入解析Java并发锁的实现哲学
java·开发语言
星火开发设计4 小时前
C++ set 全面解析与实战指南
开发语言·c++·学习·青少年编程·编程·set·知识
用户904706683574 小时前
Nuxt css 如何写?
前端
神秘的猪头4 小时前
🎨 CSS 这种“烂大街”的技术,怎么在 React 和 Vue 里玩出花来?—— 模块化 CSS 深度避坑指南
css·vue.js·react.js
夏天想4 小时前
element-plus的输入数字组件el-input-number 显示了 加减按钮(+ -) 和 小三角箭头(上下箭头),怎么去掉+,-或者箭头
前端·javascript·vue.js