0

How to compare multiple array get array result only same time in each array with javascript? consider performance

var a = [10],
    b = [],
    c = [10],
    d = [10];

get []

var a = [10],
    b = [10],
    c = [10],
    d = [10];

get [10]

var a = [0, 1, 2],
    b = [1, 2],
    c = [0, 1, 2],
    d = [0, 1, 2, 3];

get [1, 2]
user1575921
  • 1,078
  • 1
  • 16
  • 29
  • Please elaborate your question. – Rahul Desai Nov 29 '15 at 20:32
  • 2
    Duplicate of [Simplest code for array intersection in javascript](http://stackoverflow.com/q/1885557/218196) and [others](https://stackoverflow.com/search?q=[javascript]+intersection+arrays). – Felix Kling Nov 29 '15 at 20:32
  • Could someone fix that first sentence? I'm not sure what it means, but it's definitely not correct English. – Rudie Nov 29 '15 at 22:27

2 Answers2

1

This solution features a nondestructive algorithm for getting the intersection for two arrays (intersection) and a group of arrays (intersections).

function intersection(a, b) {
    var array = [];
    a.forEach(function (aa) {
        b.some(function (bb) {
            if (aa === bb) {
                array.push(aa);
                return true;
            }
        });
    });
    return array;
}

function intersections(array) {
    return array.reduce(function (a, b) {
        return intersection(a, b);
    });
}

document.write('<pre>' + JSON.stringify(intersections([[10], [], [10], [10]]), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(intersections([[10], [10], [10], [10]]), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(intersections([[0, 1, 2], [1, 2], [0, 1, 2], [0, 1, 2, 3]]), 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

_.intersection is one way :)

_.intersection([1, 2], [4, 2], [2, 1]);
// → [2]

See Lodash. This is useful if the purpose of your question is more for utility rather than academic reasons. No need to reinvent the wheel, unless it's just for learning purposes.

Josh Beam
  • 19,292
  • 3
  • 45
  • 68