I have two arrays:
var a1 = [ { ID: 2, N:0 }, { ID: 1, N:0 } ];
var a2 = [ { ID: 1, N:0 }, { ID: 2, N:0 }, { ID: 3, N:0 } ];
I need to get all
To do this efficiently, you need to build an index of the items that are already in a1 so you can cycle through a2 and compare each one to the index to see if it's already been seen or not. One can use a javascript object for an index. Cycle through a1 and put all its IDs into the index. Then cycle through a2 and collect any items whose ID does not appear in the index.
function findUniques(testItems, baseItems) {
var index = {}, i;
var result = [];
// put baseItems id values into the index
for (i = 0; i < baseItems.length; i++) {
index[baseItems[i].ID] = true;
}
// now go through the testItems and collect the items in it
// that are not in the index
for (i = 0; i < testItems.length; i++) {
if (!(testItems[i].ID in index)) {
result.push(testItems[i]);
}
}
return(result);
}
var a1 = [ { ID: 2, N:0 }, { ID: 1, N:0 } ];
var a2 = [ { ID: 1, N:0 }, { ID: 2, N:0 }, { ID: 3, N:0 } ];
var result = findUniques(a2, a1);
// [{"ID":3,"N":0}]
Working demo: http://jsfiddle.net/jfriend00/uDEtg/