多維數組 轉化為 一維數組


初級 : 將二維數組 變成 一維數組
 
 
方式一 : 使用 js api
 
(function(){
    let origin = [1,2,[3,4],5];
    let convert = origin.flat();
    console.log(convert); // display [1,2,3,4,5]
})();
 
 
方式二 : 使用 reduce + concat, 進行一級深度的扁平化處理
 
(function(){
    let origin = [1,2,3,[4,5]];
    
    function flat_with_reduce(arr){
        return arr.reduce((sum,current) => sum.concat(current),[])
    }
    
    let result = flat_with_reduce(origin);
    console.log(result);
})();

 

 
方式三 : 使用 ... + concat 進行一級深度的扁平化處理
(function(origin){
    let result = [].concat(...origin)
    console.log(result);
})([1,2,3,[4,5]]);

 

進階 : 將多維數組 轉化為 一維數組
 
方式① : 使用 reduce + concat + 遞歸
(function(origin){
    function flat_deep_with_reduce(arr){
        return arr.reduce( (sum,current) => Array.isArray(current) ? sum.concat(flat_deep_with_reduce(current) ) :  sum.concat(current) , [] );
    }
    
    let result = flat_deep_with_reduce(origin);
    console.log(result);
})([1,2,[3,4,[5,6],7],8]);
 
 
方式② : 不使用遞歸 , 使用堆棧
(function(origin){
    let stack = [...origin] ;
    let converted = [];
 
    while(stack.length){
        let item = stack.pop();    //從堆棧底部 彈出元素
        if(Array.isArray(item)){
             // 如果是數組 就扔回堆棧底部
             // 注意扔回底部的不再是 item這個數組了
             // 使用了 ... 之后 , 扔回去的就是一個 比 item少一維的數組 或者元素了
            stack.push(...item)
        }else{
            // 直到上面某個元素不是數組,將它 推給 converted 頂部
            converted.unshift(item)
        }
    }
    console.log(converted);
})([1,2,[3,4,[5,6],7],8]);

 

Polyfill

  flat 函數 , 在 IE 及 Edge版本中 得不到支持
  如果想實現 flat 函數的功能 , 只需要在原型中 加入上述滿足需要的函數即可 .
 
注 : 本文 來自於 MDN , javascript 分類中 flat() , 有需要的朋友可以參閱原文.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM