题解 | #数组扁平化#

数组扁平化

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#
题解 | 前端刷题 文章被收录于专栏

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

全部评论

相关推荐

头像 会员标识
08-20 18:46
门头沟学院 C++
投递华为技术有限公司等公司10个岗位
点赞 评论 收藏
分享
09-01 11:31
门头沟学院 Java
buul:七牛云的吧,感觉想法是好的,但是大家没那么多时间弄他这个啊。。。不知道的还以为他是顶尖大厂呢还搞比赛抢hc,只能说应试者的痛苦考察方是无法理解的,他们只会想一出是一出
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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