Z
Z
zjoin2017-02-06 19:36:39
JavaScript
zjoin, 2017-02-06 19:36:39

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}]

How to check if some object is in another array of objects? In this case, there must be one

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ivanq, 2017-02-06
@zjoin

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);

Something like that. If you need more compatibility with older versions, tell me, I'll rewrite.

S
Sergey Sokolov, 2017-02-06
@sergiks

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

T
Tsimur_S, 2017-02-06
@Tsimur_S

or just connect lodash and use find/intersection

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question