题目链接:
https://www.nowcoder.com/practice/5d7e0cf4634344c98e6ae4eaa2336bed
今天来总结一下数组扁平化的题目。
解题思路
- 遍历:for、forEach、reduce
- 判断元素是否是数组类型:instanceof、Object.prototype.toString、Array.isArray
- 递归
常规解法
1 | const arr = [1, 2, 3, 4, [1, 2, 3, [1, 2, 3, [1, 2, 3]]], 5, "string", { name: "小明" }]; |
reduce 实现 flat
使用 reduce 展开一层
1 | arr.reduce((pre, cur) => pre.concat(cur), []); |
reduce 实现 flat
1 | const flat = arr => { |
扩展运算符和 some 实现 flat
1 | const flat = arr => { |
参考文章:
https://juejin.cn/post/6844904025993773063
https://blog.csdn.net/qq_41805715/article/details/101232148