值得收藏!!javascript数组中多条对象去重方式,很实用!!!
在数组中都是数字的时候很好去重,例如:var arr=[1,2,2,2,3,4,5,4,5,3,6];可以用两层for循环或者其他方式进行去重
我在这里也给出一个方法吧:
Array.prototype.distinct = function (){ var arr = this, len = arr.length; arr.sort(function(a,b){ //对数组进行排序才能方便比较 return a - b; }) function loop(index){ if(index >= 1){ if(arr[index] === arr[index-1]){ arr.splice(index,1); } loop(index - 1); //递归loop函数进行去重 } } loop(len-1); return arr; }; var a = [1,2,3,4,5,6,5,3,2,4,56,4,1,2,1,1,1,1,1,1,56,45,56]; var b = a.distinct(); console.log(b.toString()); //1,2,3,4,5,6,45,56
在数组中都是对象的时候就需要设置布尔值来进行去重操作,原理也是两层for循环,但是在第一层for循环内需要定义布尔值为true,用来维持一个量,之后在内层for循环中进行比对,如果按照某个条件比对满足的话,布尔值就为false,之后在第一层for循环里第二层for循环外进行布尔判断,如果为真,将数据插入到新数组,如果不为真,则不用添加,从此达到了数组去重的功能,以下是代码演示
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 qcArr(arr,name){ var allArr = []; for(var i=0;i<arr.length;i++){ var flag = true; for(var j=0;j<allArr.length;j++){ if(arr[i].name == allArr[j].name){ flag = false; }; }; if(flag){ allArr.push(arr[i]); }; }; return allArr; }
去重保留最新的(最后一个)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> var oldArr = [ { busCode: "123", key: '1' }, { busCode: "123", key: '2' }, { busCode: "123", key: '3' }, { busCode: "123", key: '4' }, { busCode: "123", key: '5' }, { busCode: "123", key: '6' }, { busCode: "123", key: '7' }, { busCode: "1231", key: '8' } ]; console.log(oldArr) var allArr = [];//新数组 //websocket 加入新数据 // oldArr.unshift({ busCode: "123", key: '0' }) oldArr.push({ busCode: "123", key: '9' }) for (var i = oldArr.length - 1; i >= 0; i--) { var flag = true; for (var j = allArr.length - 1; j >= 0; j--) { if (oldArr[i].busCode == allArr[j].busCode) { flag = false; }; }; if (flag) { allArr.push(oldArr[i]); }; }; console.log(allArr) </script> </body> </html>