数组中多条对象去重方式

var oldArr = [
    {id:1,name:"zhangs",age:18,contact_id:1},
    {id:1,name:"zhangs",age:18,contact_id:2},
    {id:1,name:"zhangs",age:18,contact_id:3},
    {id:1,name:"zhangs",age:18,contact_id:14},
    {id:1,name:"zhangs",age:18,contact_id:3},
    {id:1,name:"zhangs",age:18,contact_id:2},
    {id:1,name:"zhangs",age:18,contact_id:1}
];//原数据数组
var allArr = [];//新数组

1.该方法为jquery方法

$.each(oldArr,function(i,v){
    var flag = true;
    if(allArr.length > 0){
        $.each(allArr,function(n,m){
            if(allArr[n].contact_id == oldArr[i].contact_id){flag = false;};
        });
    };
    if(flag){
        allArr.push(oldArr[i]);
    };
});


2.原生js方法

for(var i=0;i<oldArr.length;i++){
  var flag = true;
  for(var j=0;j<allArr.length;j++){
    if(oldArr[i].id == allArr[j].id){
      flag = false;
    };
  }; 
  if(flag){
    allArr.push(oldArr[i]);
  };
};

 //数组去重
  function unique(arr) {
                        return Array.from(new Set(arr))
                      }
                          
posted @ 2019-08-08 10:35  QiuYuLing  阅读(753)  评论(0编辑  收藏  举报