JS实现将数组进行扁平化处理,即将多维数组展开为一维数组
方法一、递归
function 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; } console.log(flatten(['a', ['b', 'c', [7, 8]],[4,5,[6]]]))
方法二、arrary.reduce
function flatten2(arr) { return arr.reduce((accumulator,currentValue)=> accumulator.concat(Array.isArray(currentValue) ? flatten2(currentValue) : currentValue), []); } console.log(flatten2(['a', ['b', 'c', [7, 8]],[4,5,[6]]]));
考察升级:要求这个函数接受一个参数来确定扁平化深度
function flatten_deep(arr, deep) { let result = []; if (Array.isArray(arr) && deep > 0) { for (let i = 0; i < arr.length; i++) { result = result.concat(flatten_deep(arr[i], deep - 1)); } } else { result.push(arr); } return result; } console.log(flatten_deep(['a', ['b', 'c', [7, 8]],[4,5,[6,['dd','whidhw']]]],3));