Answer the question
In order to leave comments, you need to log in
How to find the same values in two arrays of objects?
Hello everyone, there are 2 arrays of objects, for example:[{"id":1, "item": 213}]
[{"id":1, "item": 213}, {"id":78, "item": 21}, {"id":19, "item": 13}]
Answer the question
In order to leave comments, you need to log in
var a = [{"id":1, "item": 213}];
var b = [{"id":1, "item": 213}, {"id":78, "item": 21}, {"id":19, "item": 13}];
var result = a.filter(function(v) {
return b.some(function(v2) {
return v.id == v2.id && v.item == v2.item;
}
});
console.log(result);
For two arrays of strings or numbers, the algorithm would be:
You can apply the algorithm, knowing the features of this particular problem. It is known that there are two fields, called id and item, their values are integers. Let's make an array of pseudo-hashes from each, so that instead of an array of objects we deal with an array of strings.
function haveCommon(a,b) {
var phash = function(e){ return '' + e.id + '.' + e.item }
,ha = a.map(phash).sort()
,hb = b.map(phash).sort()
,ia = 0
,ib = 0
;
while( ia<ha.length && ib<hb.length) {
if( ha[ia] > hb[ib]) ib++;
else if( ha[ia] < hb[ib]) ia++;
else return true;
}
return false;
}
haveCommon( [{"id":1, "item": 213}]
,[{"id":1, "item": 213}, {"id":78, "item": 21}, {"id":19, "item": 13}]
) // true
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question