Several methods of object deduplication

Object array deduplication is not as simple as array deduplication, but the idea is similar to array deduplication. Let’s briefly talk about some ideas of object array deduplication.

Deduplication of an object array is to loop the array object twice to determine whether each object and a certain attribute value of each object are the same.

 

<script src="../../../../../../../ios/jquery.min.js"></script>
<script>
//Requirement: put each element in the array Removal of the same id in each object
// native js
// original data array
var oldArr = [
{ id: 1, name: "zhangs", age: 18, contact_id: 1 },
{ id: 1, name: "zhangs" , age: 18, contact_id: 2 },
{ id: 3, name: "zhangs", age: 18, contact_id: 3 },
{ id: 4, name: "zhangs", age: 18, contact_id: 14 },
{ id: 1, name: "zhangs", age: 18, contact_id: 3 },
{ id: 6, name: "zhangs", age: 18, contact_id: 2 },
{ id: 7, name: "zhangs" , age: 18, contact_id: 1 }
];
for (var i = 0; i < oldArr.length; i++) {
// don't need to compare with yourself,compared no need to compare
for (var j = i + 1; j < oldArr.length; j++) {
console.log(i, j, 'ok');
if (oldArr[i].id == oldArr[j].id) {
console.log(i, j);
oldArr.splice(j, 1);
}
}
}
console.log(oldArr);
// 第二种方法
var oldArr2 = [
{ id: 1, name: "zhangs", age: 18, contact_id: 1 },
{ id: 1, name: "zhangs", age: 18, contact_id: 2 },
{ id: 3, name: "zhangs", age: 18, contact_id: 3 },
{ id: 4, name: "zhangs", age: 18, contact_id: 14 },
{ id: 1, name: "zhangs", age: 18, contact_id: 3 },
{ id: 6, name: "zhangs", age: 18, contact_id: 2 },
{ id: 7, name: "zhangs", age: 18, contact_id: 1 }
];
var empty = [];
for (var i = 0; i < oldArr2.length;i ++) {
var cp = true;
for (var j = i + 1; j < oldArr2.length; j++) {
if (oldArr2[i].id == oldArr2[j].id) {
cp = false;
}
}
if (cp) {
empty.push(oldArr2[i]);
}
}
console.log(empty);
// jq的方法
var oldArr = [
{ id: 1, name: "zhangs", age: 18, contact_id: 1 },
{ id: 2, name: "zhangs", age: 18, contact_id: 2 },
{ id: 3, name: "zhangs", age: 18, contact_id: 3 },
{ id: 4, name: "zhangs", age: 18, contact_id: 14 },
{ id: 1, name: "zhangs", age: 18, contact_id: 3 },
{ id: 4, name: "zhangs", age: 18, contact_id: 2 },
{ id: 1, name: "zhangs", age: 18, contact_id: 1 }
];
var allArr = []; //new array
$.each(oldArr, function(i, v) {
var flag = true;
if (allArr.length > 0) {
$.each(allArr, function(n, m) {
if (allArr[n].id == oldArr[i].id) { flag = false; };
});
};
// the first time allArr is empty, after this operation makes allArr have new data
if (flag) {
allArr.push(oldArr[i ]);
};
});
console.log(allArr);

</script>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325001844&siteId=291194637