0%

数组扁平化

题目链接:
https://www.nowcoder.com/practice/5d7e0cf4634344c98e6ae4eaa2336bed

今天来总结一下数组扁平化的题目。

解题思路

  1. 遍历:for、forEach、reduce
  2. 判断元素是否是数组类型:instanceof、Object.prototype.toString、Array.isArray
  3. 递归

常规解法

1
2
3
4
5
6
7
8
9
10
11
12
const arr = [1, 2, 3, 4, [1, 2, 3, [1, 2, 3, [1, 2, 3]]], 5, "string", { name: "小明" }];
function flat(arr) {
let res = [];
arr.forEach(item => {
if(Array.isArray(item)) {
res = res.concat(flat(item));
} else {
res.push(item);
}
})
return res;
}

reduce 实现 flat

使用 reduce 展开一层

1
arr.reduce((pre, cur) => pre.concat(cur), []);

reduce 实现 flat

1
2
3
4
5
const flat = arr => {
return arr.reduce((pre, cur) => {
return pre.concat(Array.isArray(cur) ? flat(cur) : cur);
}, [])
}

扩展运算符和 some 实现 flat

1
2
3
4
5
6
const flat = arr => {
while(arr.some(item => Array.isArray(item))) {
arr = [].concat(...arr);
}
return arr;
}

参考文章:
https://juejin.cn/post/6844904025993773063
https://blog.csdn.net/qq_41805715/article/details/101232148

本文标题:数组扁平化

文章作者:Flower-F

发布时间:2021年12月10日 - 12:23

最后更新:2022年01月19日 - 16:40

-------------本文结束,感谢您的阅读-------------

欢迎关注我的其它发布渠道