Array to array weight and flat

一、数组去重
(1)indexOf()
function only(arr){
    var res=[];
    arr.forEach(function(item){
        if(res.indexOf(item)==-1){
            res.push(item);
        }
    })
    return res;
}

(2) Set structure

var set=new Set(arr);
Array.from(set);

(3) filter filters

function only(arr){
    var res=[];
    res=arr.filter(function(item,index,self){
        if(self.indexOf(item)==index){
            return item;
        }
    })
    return res;
}

(4)reduce()

function only(arr){
    var res=[];
    return arr.reduce((pre,cur)=>{
        if(!pre.includes(cur)){
            return pre.concat(cur);
        }
        else{
            return pre;
        }
    },[])
}

 


二、数组扁平化处理可以用reduce

例:实现一个flatten方法,使得输入一个数组,该数组里面的元素也可以是数组,该方法会输出一个扁平化的数组。
arr=[[1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14]]]], 10];
console.log([1,2,2,3,4,5,5,6,7,8,9,11,12,12,13,14,10]);

(1)递归

Copy the code
function flatten(arr){
      var res=[];
     for(var i=0;i<arr.length;i++){
          if(Array.isArray(arr[i])){
                 res=res.concat(flatten(arr[i]));
            }
         else{
                 res.push(arr[i]);
            }
        }
       return res;
}       
Copy the code
 

(2)reduce()

function flatten(arr){
      return arr.reduce(function(pre,item){
             return pre.concat(Array.isArray(item)?flatten(item):item);
      },[]);
}

(3)map()

Copy the code
function flatter2(arr){
    var res=[];
    arr.map(function(item){
        if(Array.isArray(item)){
            res=res.concat(flatter2(item));
        }
        else{
            res.push(item);
        }
    })
    return res;
}
Copy the code

Guess you like

Origin www.cnblogs.com/xiaoan0705/p/11263278.html