简体   繁体   中英

Intersection of values of 2 arrays of objects

I have 2 arrays in the form:

array1 = [{key1: value1}, {key1: value2}, ...];
array2 = [{key2: value0}, {key2: value2}, ...];

where the object keys in both arrays are different, but the values may match. I would like to write some code that gets the intersection between the two arrays where in the above example, it should return: [value2] .

I tried using:

array1.filter(function(n)) {
    return array2.indexOf(n) != -1;
});

but of course I got an empty array because the keys mismatch. Can the above code be modified to ignore the object keys and match only their values?

    var kiran = [];
    var array1 = [{ key1: 'value1' }, { key1: 'value2' }];
    var array2 = [{ key2: 'value0' }, { key2: 'value2' }];
    array1.map(function(item1){
       array2.map(function(item2){
         if(item1.key1 === item2.key2){
           kiran.push(item2.key2);
         }
       })
    })
    console.log(kiran);

How about below approach

 const array1 = [{ key1: 'value1' }, { key1: 'value2' }]; const array2 = [{ key2: 'value0' }, { key2: 'value2' }]; const result = array1.filter(c => array2.findIndex(x=>x.key2 == c.key1) > -1) console.log(result);

You could use a hash table and with a binary value. Then check if the count is equal to three, then take that key as result.

 var array1 = [{ key1: 'value1' }, { key1: 'value2' }], array2 = [{ key2: 'value0' }, { key2: 'value2' }], hash = Object.create(null), incHash = function (i) { return function (o) { Object.keys(o).forEach(function (k) { hash[o[k]] = (hash[o[k]] || 0) | 1 << i; }); }; }, result; [array1, array2].forEach(function (a, i) { a.forEach(incHash(i)); }); result = Object.keys(hash).filter(function (k) { return hash[k] === 3; }); console.log(result); console.log(hash);

If you can use third party library then I suggest Lodash . An incredibly usefull utility library.

You can use _.intersectionWith() funciton to get your task done in one line

 var array1 = [{ key1: 'value1' }, { key1: 'value2' }], array2 = [{ key2: 'value0' }, { key2: 'value2' }]; var intersection = _.map(_.intersectionWith(array1, array2, function(item1,item2){ return item1.key1 === item2.key2; }),'key1'); console.log(intersection);
 <script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"> </script>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM