JavaScript数组扁平化(flat)方法总结

85 阅读1分钟

需求:多维数组 ⇒ 一维数组

let arr = [1, [2, [3, [4, 5]]], 6]; 

1.方法一,10万次运算耗时388ms
let str = JSON.stringify(arr);
let res = str.replace(/[\\[\\]]/g,"").split(",").map(i => Number(i));
// [1, 2, 3, 4, 5, 6]

2.方法二,10万次运算耗时367ms
let str = JSON.stringify(arr);
let res = JSON.parse("[" + str.replace(/[\\[\\]]/g,"") + "]")
// [1, 2, 3, 4, 5, 6]

3.方法三,递归处理,10万次运算79ms
let res = [];
let fn = function(arr){
	arr.forEach(item => {
		if(Array.isArray(item)){
				fn(item);
		}else{
			res.push(item);
		}
	})
}
fn(arr);
res // [1,2,3,4,5,6]

4.方法四,数组的reduce方法,10万次运算63523ms
let flatArray = arr => arr.reduce((a,b)=> a.concat(Array.isArray(b)? flatArray(b): b), [])
flatArray(arr);
// [1, 2, 3, 4, 5, 6]

5.拓展运算符,10万次运算耗时26ms
while (arr.some(Array.isArray)){
	arr = [].concat(...arr);
}
// [1, 2, 3, 4, 5, 6]