用JavaScript展平数组。
我们需要编写一个JavaScript数组函数,该函数接受一个嵌套数组,并返回一个数组,其中包含数组中存在的所有元素而没有任何嵌套。
例如-
//if the input is: const arr = [[1, 2, 3], [4, 5], [6]]; //那么输出应该是: 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 ]