Compare two array of objects to find distinct values by key number
Suppose the old object consists of
oldChoices = [{"number": 1, "text": "abc" }, {"number": 2, "text": "pqr" }]
and new object consists of
newChoices = [{"number": 1, "text": "abc" }, {"number": 2, "text": "pqr" }, {"number": 3, "text": "xyz" }]
So need to get:
[{"number": 3, "text": "xyz" }]
Note: 1. Values populate in the newChoices array on the keypress event of the textbox. 2. newChoices can get value at the start as well.
Attempt 1:
var uniqueTemp = [];
$.each(oldChoices, function(x, e1){
$.each(newChoices, function(y, e2){
if(e1.number != e2.number){
uniqueTemp.push(e2);
}
});
})
Attempt 2:
var uniqueTemp = [];
oldChoices.filter(function(x){
if(newChoices.indexOf(x.number) === -1){
uniqueTemp.push(x);
return true;
}else{
return false;
}
});
Expected:
[{"number": 3, "text": "xyz" }]