JS陣列扁平化(flat)
阿新 • • 發佈:2022-03-22
let ary = [1, [2, [3, [4, 5]]], 6];
let str = JSON.stringify(ary);
用 reduce 實現陣列的 flat 方法 function flatten(ary){ return ary.reduce((pre,cur)=>{ return pre.concat(Array.isArray(cur)?flatten(cur):cur) },[]) } flatten( [1, 2, [3, 4], [5, [6, 7]]]) 遞迴 let result = []; let fn = function(ary) { for(let i = 0; i < ary.length; i++) }{ let item = ary[i]; if (Array.isArray(ary[i])){ fn(item); } else { result.push(item); } } } 擴充套件運算子 while (ary.some(Array.isArray)) { ary = [].concat(...ary); }
- flat([1, 2, 3, [4, 5]]) // [1,2,3,4,5]
- flat([1, 2, 3, [[4, 5]]]) // [1,2,3,[4,5]]
- flat([1, 2, 3, [[4, 5]]], 2) // [1,2,3,4,5]
- flat([1,2,3,[1,2,[1,2,3]]]) [1,2,3,1,2,[1,2,3]]
function flat(array, depth=1) { let result=[] for (let i = 0; i < array.length; i++) { let item = array[i] if (depth > 0 && Array.isArray(item)) { result = result.concat(flat(item, depth - 1)) } else { result.push(item) } } return result }
function flat(array, depth = 1) { let count = 0 let result = array while (count < depth) { for (let i = 0; i < result.length; i++) { // 如果是陣列,則將此項拍平 if (Array.isArray( result[i])) { let item=result.splice(i, 1) result = [...result, ...item] } } count++ } return result }
function flat(array, depth = 1) {
return array.reduce((result, item) => {
if (depth > 0 && Array.isArray(item)) {
result = [
...result,
...flat(item, depth - 1)
]
} else {
result.push(item)
}
return result
}, [])
}
function flat(array,depth=1){
return depth>0?array.reduce((pre,cur)=>{
return pre.concat(Array.isArray(cur)?flat(cur,depth-1):cur)
},[]):array.slice()
}
flat([1,2,3,[1,2,[1,2,3]]])