Mostafiz Mostafiz - 2 months ago 8
Javascript Question

Get some set of array based on condition from two arrays of array in Javascript

I have two arrays of array in Javascript like

var array1 = [[10, 2], [11, 4], [12, 30], [13, 17], [14, 28]];
var array2 = [[8, 13], [9, 19], [10, 6], [11, 7], [12, 1]];


I want to get the set of arrays from
array1
which match the first element of each array of the
array2


in my example case both
array1
and
array2
have array with first element as
10
11
and
12
, so it should return

[[10, 2], [11, 4], [12, 30]];


is there any easy and efficient way using pure javscript or lodash, underscor framework or something like that. Without iterate over and match one by one of this two array ?

Answer

In ES6, you could use Set.

var array1 = [[10, 2], [11, 4], [12, 30], [13, 17], [14, 28]],
    array2 = [[8, 13], [9, 19], [10, 6], [11, 7], [12, 1]],
    set = new Set(array2.map(a => a[0])),
    result = array1.filter(a => set.has(a[0]));

console.log(result);

Version with an object as hash table

var array1 = [[10, 2], [11, 4], [12, 30], [13, 17], [14, 28]],
    array2 = [[8, 13], [9, 19], [10, 6], [11, 7], [12, 1]],
    result = array1.filter(function (a) {
        return this[a[0]];
    }, array2.reduce(function (r, a) { 
        r[a[0]] = true;
        return r;
    }, Object.create(null)));

console.log(result);