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;
}
相关推荐
lichenyang4531 小时前
React ajax中的跨域以及代理服务器
前端·react.js·ajax
呆呆的小草1 小时前
Cesium距离测量、角度测量、面积测量
开发语言·前端·javascript
uyeonashi1 小时前
【QT系统相关】QT文件
开发语言·c++·qt·学习
WHOAMI_老猫1 小时前
xss注入遇到转义,html编码绕过了解一哈
javascript·web安全·渗透测试·xss·漏洞原理
一 乐2 小时前
民宿|基于java的民宿推荐系统(源码+数据库+文档)
java·前端·数据库·vue.js·论文·源码
冬天vs不冷2 小时前
Java分层开发必知:PO、BO、DTO、VO、POJO概念详解
java·开发语言
sunny-ll2 小时前
【C++】详解vector二维数组的全部操作(超细图例解析!!!)
c语言·开发语言·c++·算法·面试
testleaf2 小时前
前端面经整理【1】
前端·面试
好了来看下一题2 小时前
使用 React+Vite+Electron 搭建桌面应用
前端·react.js·electron
啃火龙果的兔子2 小时前
前端八股文-react篇
前端·react.js·前端框架