数组扁平化:指将一个多层数组嵌套扁平化为一个数组
例如:
[1,[2,[3]]] => [1,2,3]
1.递归
let arr = [1,[2,[3,[4,5]]]]
function flatten(arr){
let result = []
for(var i = 0;i < arr.length; i++){
if(Array.isArray(arr[i])){
result = result.concat(flatten(arr[i]))
}else{
result.push(arr[i])
}
}
return result
}
console.log(flatten(arr))
2.reduce
let arr = [1,[2,[3,[4,5]]]]
function flatten(arr){
return arr.reduce((result,current,currentIndex)=>{
return result.concat(Array.isArray(current)?flatten(current):current)
},[])
}
console.log(flatten(arr))
3.ES6解构运算符(…)
let arr = [1,[2,[3,[4,5]]]]
function flatten(arr){
while(arr.some(item=>Array.isArray(item))){
arr=[].concat(...arr)
}
return arr
}
console.log(flatten(arr))
4.underscore中的实现方式
源码地址:https://github.com/jashkenas/underscore/blob/master/underscore.js#L533
@param {Array} input //要处理的数组
@param {Boolean} shallow //是否只扁平化一层
@param {Boolean} strict //当元素不是数组时,根据strict判断是过滤掉该元素还是直接放入output
@output {Array} output //输出结果
function flatten(input,shallow,strict,output){
output = output || []
var idx = output.length
for(var i = 0,len = input.length;i<len;i++){
var value = input[i]
if(Array.isArray(value)){ //是数组
if(shallow){ //只扁平化一层
var j = 0,length = value.length
while(j < length) output[idx++] = value[j++]
}else{ //全部扁平化,递归
flatten(value,shallow,strict,output)
idx = output.length
}
}else if(!strict){ //不是数组,根据strict判断是跳过不处理还是放入output
output[idx++] = value
}
}
return output
}
let arr = [1,[2,[3]]]
let r = flatten(arr,false,false)
console.log(r)
参考文章:https://github.com/mqyqingfeng/Blog/issues/36
感谢!