1. es6 flat
console.log([1 ,[2, 3]].flat()) // [1, 2, 3]
console.log([1, [2, [3, [4, 5]]]].flat()) // [1, 2, Array(2)]
// 指定转换的嵌套层数
console.log([1, [2, [3, [4, 5]]]].flat(2)) // [1, 2, 3, [4, 5]]
// 不管嵌套多少层
console.log([1, [2, [3, [4, 5]]]].flat(Infinity)) // [1, 2, 3, 4, 5]
// 自动跳过空位
console.log([1,[2, , 3]].flat()) // [1, 2, 3]
2.es6 ...拓展运算符
var entries=[1,[2,5],[6,7],9]
var flat_entries = [].concat(...entries)
console.log(flat_entries) //[1, 2, 5, 6, 7, 9]
3.递归实现数组扁平化
const flatten = arr=>{
let result = []
for (let i = 0; i < arr.length; i++) {
if(Array.isArray(arr[i])){
result = result.concat(flatten(arr[i]))
}else{
result.push(arr[i])
}
}
return result
}
4.reduce实现
function fn(arr){
return arr.reduce((prev,cur)=>{
return prev.concat(Array.isArray(cur)? fn(cur):cur)
},[])
}
5.while实现
// 利用: arr =[]. concat (.…. arr )
//arr . some ( ele => {
// return Array . isArray ( ele );
// })
function myFlat ( arr ){
while ( arr.some ( Array.isArray ) ){
arr =[]. concat (… arr )
}
return arr ;
}
let arr2=[1,[2,[3,[6,[7]]1],4,5];
const newArr2= myFlat (arr2);
console . log (newArr2);
面试题
// 要求实现一个函数
const flatten =(list,level =Infinity)=>{
// ...
}
const array = [1,[2,[3,4,[5]],3]]
const list1 = flatten(array)
const list2 = flatten(array,2)
解答:
const flatten = (list, level = +Infinity) => {
let res = list
for (let i = 0; i < level; i++) {
res = [].concat(...res)
if (!res.some(item => Array.isArray(item))) break
}
return res
}