One, recursive solution
const arr = [1,[[2,3],4],[5,6]];
function flat(array){
let flatA = [];
array.forEach((item,index) =>{
if(item instanceof Array){
flatA = flatA.concat(flat(item))
}else{
flatA.push(item)
}
})
return flatA
}
console.log(flat(arr))//[1,2,3,4,5,6]
Second, use the Generator function
const arr = [1,[[2,3],4],[5,6]];
function* flat(a){
var len = a.length;
for(var i =0 ; i< len ; i++){
var item = a[i];
if(typeof item !== 'number'){
yield* flat(item)
}else{
yield item
}
}
}
const flatArr = []
for(var f of flat(arr)){
console.log(f)
flatArr.push(f)
}
console.log(flatArr) //[1,2,3,4,5,6]
Three, reduce + recursion
const arr = [1,[2,3,4],[5,6]];
function flat(arr){
return arr.reduce((prev,next) => {
return prev.concat((next instanceof Array) ? flat(next):next)
},[])
}
console.log(flat(arr)); //[1,2,3,4,5,6]
Four, flat method
The flat method of the array is used to return a new array without changing the original array.
The parameter accepts a number, the default is 1, for a flattening
const arr = [1,2,3,[[4,4,4],5],[6,7]];
const arr1 = arr.flat();
console.log(arr1) //[1,2,3,[4,4,4],5,6,7]
Pass parameters:
const arr = [1,2,3,[[4,4,4],5],[6,7]];
const arr1 = arr.flat(2);
console.log(arr1) //[1, 2, 3, 4, 4, 4, 5, 6, 7]
The parameter can be passed Infinity, no matter how deep the array is nested, it can be converted to a one-dimensional array:
const arr = [1,2,3,[[4,[4,4]],5],[6,7]];
const arr1 = arr.flat(Infinity);
console.log(arr1) //[1, 2, 3, 4, 4, 4, 5, 6, 7]