将一个数组展平为 Javascript。
我们需要编写一个 JavaScript 数组函数,该函数接受一个嵌套数组,并返回一个包含数组中所有元素的数组,不包含任何嵌套。
例如 −
//if the input is: const arr = [[1, 2, 3], [4, 5], [6]]; //then the output should be: const output = [1, 2, 3, 4, 5, 6];
因此,让我们为这个函数编写代码 −
方法 1:使用递归
这里我们将循环遍历原始的嵌套数组,并递归地将嵌套元素元素推送到一个新数组中。
示例
const arr = [[1, 2, 3], [4, 5], [6]];
const flatten = function(){
let res = [];
for(let i = 0; i < this.length; i++){
if(Array.isArray(this[i])){
res.push(...this[i].flatten());
} else {
res.push(this[i]);
};
};
return res;
};
Array.prototype.flatten = flatten;
console.log(arr.flatten());方法 2:使用 Arrray.prototype.reduce()
这里我们将使用 reduce() 方法构造一个类似这样的新数组 −
示例
const arr = [[1, 2, 3], [4, 5], [6]];
const flatten = function(){
return this.reduce((acc, val) => {
return acc.concat(...val);
}, []);
};
Array.prototype.flatten = flatten;
console.log(arr.flatten());输出
这两种方法的控制台输出为 −
[ 1, 2, 3, 4, 5, 6 ]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP