wonderbeyond
4/1/2017 - 2:19 AM

[javascript] Get array intersection, support array of objects by key.

[javascript] Get array intersection, support array of objects by key.

var res = intersect([
    {
        'id': 1
    }, {
        'id': 2,
        'name': 'xx2'
    }, {
        'id': 3
    }
], [
    {
        'id': 2,
        'name': 'Xx22'
    }, {
        'id': 3
    }, {
        'id': 4
    }
], 'id');

console.log(res);
console.log(intersect([1, 2, 3], [2, 3, 4]));

var arrs = [
    [1, 2, 3],
    [2, 3, 4],
    [3, 4, 5],
];

var res = arrs.reduce((L, R) => intersect(L, R));
console.log(res);
function intersect(a, b, key) {
    if (b.length > a.length) {
        [a, b] = [b, a];
    }

    if (key) {
        var refVars1 = a.map((item) => item[key]);
        var refVars2 = b.map((item) => item[key]);
    } else {
        var [refVars1, refVars2] = [a, b];
    }

    return refVars1.map(function(v) {
        return refVars2.indexOf(v);
    }).filter(v => v >= 0).map(idx => b[idx]);
}