美文网首页
arr.flat数组扁平化+去重排序

arr.flat数组扁平化+去重排序

作者: divcssjs | 来源:发表于2019-08-08 17:21 被阅读0次

    之前最简单的写法

    let arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];
    let newarr = Array.from(new Set(arr.toString().split(','))).sort((a,b)=>a-b)
    //["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"]
    
    arr.toString()  //"1,2,2,3,4,5,5,6,7,8,9,11,12,12,13,14,10"
    .split(',')    //["1", "2", "2", "3", "4", "5", "5", "6", "7", "8", "9", "11", "12", "12", "13", "14", "10"]s
    .sort((a,b)=>a-b)      //["1", "2", "2", "3", "4", "5", "5", "6", "7", "8", "9", "10", "11", "12", "12", "13", "14"]
    
    //new Set 去重  > 对象
    //Array.from() 对象>数组
    

    es10的arr.flat

    Array.from(new Set(arr.flat(Infinity))).sort((a,b)=>{ return a-b})
    

    可以看出

    arr.flat() === arr.toString().split(',')  === 数组扁平化
    
    封装一个flat,方式一
    Array.prototype.flat=function(){
      var arr = [];
      this.forEach( k =>{
        if(Array.isAttay(K)){
            arr=arr.concat(k.flat())  //如果是数组,继续循环
        }else{
            arr.push(k)
        }
      })
      return arr
    }
    
    封装一个flat,方式二
    Array.prototype.flat = funtion(){
      return this.toString()  
                  //"1,2,2,3,4,5,5,6,7,8,9,11,12,12,13,14,10"
                  .split(',')    
                  //["1", "2", "2", "3", "4", "5", "5", "6", "7", "8", "9", "11", "12", "12", "13", "14", "10"]s
                  .sort((a,b)=>a-b)      
                  //["1", "2", "2", "3", "4", "5", "5", "6", "7", "8", "9", "10", "11", "12", "12", "13", "14"]
    }
    console.log([1,[2,[3,4]]].flat())//[1, 2, 3, 4]
    

    相关文章

      网友评论

          本文标题:arr.flat数组扁平化+去重排序

          本文链接:https://www.haomeiwen.com/subject/mftfjctx.html