数组扁平化:
输入:const data = [ 1,2 ,[3,4,6,8],[1,2,[2]]];
输出:[1,2,3,4,6,8,1,2,2]
方法总结
- 数组自带的flat
- 递归
- reduce ,concat结合做递归
- 循环递归
- 扩展运算符
- 利用字符串
- 通过json
- 栈加扩展运算符
1. Array.prototype.flat()
The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth
arr.flat(Infinity);
2. Array.reduce
const flatten = function( arr ){
return arr.reduce(( prev,cur)=>{
return prev.concat( Array.isArray(cur) ? flatten( cur) : cur );
},[])
}
3. 扩展运算符
const flatten1 = function( arr ){
while( arr.some( item => Array.isArray(item))){
arr = [].concat(...arr)
}
return arr;
}
4. 递归
function flatten(arr) {
var res = [];
arr.map(item => {
if(Array.isArray(item)) {
res = res.concat(flatten(item));
} else {
res.push(item);
}
});
return res;
}
5. toString ,split
const flatten = function( arr ){
return arr.toString().spilt(',').map( item=>{
return item
})
}
6. join ,split
const flatten = function( arr ){
return arr.join(',').split(',').map( item=>{
return item
})
}
7. 正则
数据类型都会变为字符串,如需要,map做解析
const res = JSON.stringify(arr).replace(/\[|\]/g, '').split(',');
8. 正则二
const res = JSON.parse('[' + JSON.stringify(arr).replace(/\[|\]/g, '') + ']');
9. 栈
const flatten = function( arr ){
const stack = [...arr];
let res = [];
while ( stack.length ) {
const next = stack.pop();
if( Array.isArray(next) ){
stack.push(...next);
}else{
res.push(next);
}
}
return res.reverse();
}