Handwritten array flattening
Problem description:
input depth array such as [1, 2, [3, 4, 5, [6, 7]]]
output [1,2,3,4,5,6,7] into an array without changing the original in order
Code demo:
//手写数组扁平化
function flat(arr) {
const isDeep = arr.some(item => item instanceof Array); //判断数组是否是深度数组,
if (!isDeep) {
return arr;//不是深度数组直接返回结果
} else {
const res = Array.prototype.concat.apply([], arr);//是深度数组进行扁平化
return flat(res); //递归操作,如果拍一次还有深度数组就继续判断 直到没有深度数组直接返回结果跳出递归
}
}
const res = flat([1, 2, [3, 4, 5, [6, 7]]]) //验证
console.log(res);
Output result: