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

I have two array arrays in Javascript for example

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 a set of arrays from array1which correspond to the first element of each arrayarray2

in my example, an example: array1and array2have an array with the first element as 10 11and 12, therefore, it should return

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

is there a simple and efficient way using pure javscript or lodash, underscor framework or something like that. Without iterating and matching on one of these two arrays?

+4
source share
5 answers

ES6 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);
Hide result

-

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);
Hide result
+4

lodash _. intersectWith, .

_.intersectionWith(array1, array2, function(a, b) {
    return a[0] === b[0];
});

, . , . fiddle, .

+3

Set, .filter , :

var haystack = new Set(array2.map(x => x[0]));
var newArray = array1.filter(x => haystack.has(x[0]));

, lodash underscore .map .filter.


Set :

  • indexOf . :

    var haystack = array2.map(x => x[0]);
    var newArray = array1.filter(x => haystack.indexOf(x[0]) > -1);
    
  • number -> true in, hasOwnProperty :

    var haystack = array2.reduce((obj, x) => (obj[x[0]] = true, obj), {});
    var newArray = array1.filter(x => haystack[x[0]]);
    

, , , , .

+2

filter() find()

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

var result = array1.filter(function(ar) {
  return array2.find(function(e) {
    return e[0] == ar[0]
  })
})

console.log(result)
Hide result
+1

Map anf filter ES6 :

var array1 = [[10, 2], [11, 4], [12, 30], [13, 17], [14, 28]],
    array2 = [[8, 13], [9, 19], [10, 6], [11, 7], [12, 1]],
         m = new Map(array2),
    array3 = array1.filter(a => m.has(a[0]));
console.log(array3);
Hide result

, .

0

Source: https://habr.com/ru/post/1656846/


All Articles