I have two array of objects:
1) [{id:1}{id:2}{id:3}{id:4}{id:5}]
2) [{id:1}{id:2}{id:3}]
is there any in build function in UnderscoreJS or AngularJS which will give me the output as :
[{id:4}{id:5}]
I tried using the _.difference
and _.without
but this is not working as they work on simple arrays not on array of objects
Thanks in advance.
function diff(a, b) {
return _.filter(a, function(val) {
return !_.findWhere(b, val);
});
}
diff[{id:1}, {id:2}, {id:3}, {id:4}, {id:5}], [{id:1}, {id:2}, {id:3}]); // [{id:4}, {id:5}]
this solution is specific to this data structure and will not work for any array of objects.
I have a stupid way, but it seems to explain the problem.
//arr1.length >= arr2.length
function diff(arr1,arr2){
var array1 = new Array();
var array2 = new Array();
array1 = array1.concat(arr1);
array2 = array2.concat(arr2);
for (var i = array1.length - 1; i >= 0; i--) {
//instead "id" or other
var idVal = array1[i].id;
for (var j = array2.length - 1; j >= 0; j--) {
if(idVal == array2[j].id) {
//delete the object in array1 and array2
array1.del(i);
array2.del(j);
};
};
};
return array1.concat(array2);
}
Array.prototype.del = function ( dx ) {
if (isNaN(dx) || dx > this.length) {
return false;
}
for (var i = 0, n = 0; i < this.length; i++) {
if (this[i] != this[dx]) {
this[n++] = this[i]
}
}
this.length -= 1
}
Array.prototype.unique = function () {
var r = new Array();
label:for(var i = 0, n = this.length; i < n; i++) {
for(var x = 0, y = r.length; x < y; x++) {
if(r[x].id == this[i].id) {
continue label;
}
}
r[r.length] = this[i];
}
return r;
}
var array1 = [{id:"1"},{id:"2"},{id:"3"},{id:"4"},{id:"12"},{id:"15"},{id:"15"}].unique();
var array2 = [{id:"1"},{id:"2"},{id:"03"},{id:"4"},{id:"5"},{id:"5"},{id:"5"},{id:"5"},{id:"5"}].unique();
var resultArray = array1.length >= array2.length
? diff(array1,array2) : diff(array2,array1);
console.log(resultArray);
//[ { id: '3' },{ id: '12' },{ id: '15' },{ id: '03' },{ id: '5' } ]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.