题解 | #数组扁平化#

数组扁平化

https://www.nowcoder.com/practice/5d7e0cf4634344c98e6ae4eaa2336bed

在JavaScript中,有几种方法可以将多维数组扁平化成一维数组。下面介绍几种常见的实现方法:

  1. 递归方法:
function flattenArray(arr) {
  let result = [];
  arr.forEach(item => {
    if (Array.isArray(item)) {
      result = result.concat(flattenArray(item));
    } else {
      result.push(item);
    }
  });
  return result;
}

const nestedArray = [1, [2, [3, 4], 5], 6];
const flattenedArray = flattenArray(nestedArray);
console.log(flattenedArray); // [1, 2, 3, 4, 5, 6]
  1. 使用reduce方法:
function flattenArray(arr) {
  return arr.reduce((result, item) => {
    return result.concat(Array.isArray(item) ? flattenArray(item) : item);
  }, []);
}

const nestedArray = [1, [2, [3, 4], 5], 6];
const flattenedArray = flattenArray(nestedArray);
console.log(flattenedArray); // [1, 2, 3, 4, 5, 6]
  1. 使用ES6的展开运算符:
function flattenArray(arr) {
  while (arr.some(item => Array.isArray(item))) {
    arr = [].concat(...arr);
  }
  return arr;
}

const nestedArray = [1, [2, [3, 4], 5], 6];
const flattenedArray = flattenArray(nestedArray);
console.log(flattenedArray); // [1, 2, 3, 4, 5, 6]

这些方法都可以将多维数组扁平化成一维数组,你可以根据自己的需求选择其中一种实现方式。

#JavaScript#
题解 | 前端刷题 文章被收录于专栏

题目考察的知识点 题目解答方法的文字分析 本题解析所用的编程语言 完整且正确的编程代码

全部评论

相关推荐

10-22 19:44
门头沟学院 Java
面了100年面试不知...:那我得去剪个头
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务