0

new to javascript. i have these two arrays

var array1 = [['1'],['2']];
var array2 = [['2'],['3'],['4']];

how can i find the matching values?

tried below but returns empty array probably because it's for normal array structure ['', '', '']

var matchingValue = array1.filter(value => array2.includes(value));
Logger.log(matchingValue);

Matching value should be ['2']

tiredqa_18
  • 162
  • 2
  • 9

4 Answers4

2

You can simply use .flat() to flatten the arrays so you only deal with the values like so :-

var array1 = [['1'],['2']];
var array2 = [['2'],['3'],['4']];

var matchingValue = array1.flat().filter((value) => array2.flat().includes(value) )
console.log(matchingValue);
Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39
  • brilliant. i never knew about flat before! thanks for the answer and introducing flat to me. appreciate your help! – tiredqa_18 Jun 01 '21 at 09:09
2

First, let's have a function that tells if two arrays are equal:

let equal = (a, b) => a.length === b.length && a.every((_, i) => a[i] === b[i])

Then, use this function to find an intersection of two arrays:

var array1 = [['1'],['2']];
var array2 = [['2'],['3'],['4']];

let equal = (a, b) => a.length === b.length && a.every((_, i) => a[i] === b[i])

result = array1.filter(x => array2.some(y => equal(x, y)))

console.log(result)

In a more generic way, you can write intersectBy that would compute an intersection using a predicate callback:

let intersectBy = (a, b, predicate) => 
   a.filter(x => b.some(y => predicate(x, y)))   
georg
  • 211,518
  • 52
  • 313
  • 390
0

Array.includes compares by identity, so it works with primitives and not with Array and Objects.

This is a solution that compares the first element of the internal arrays:

var matchingValue = array1.filter(value1 => {
  return array2.map(value2 => value2[0]).includes(value1[0]);
});

Array.map is used to convert an Array of Arrays in Array of strings, then Array.includes is used to match the first element of first Array.

This works only with the current structure (arrays of one element arrays).

DanieleAlessandra
  • 1,380
  • 1
  • 12
  • 21
0

const array1 = [['1'],['2']];
const array2 = [['2'],['3'],['4']];

const array1Flat = [].concat(...array1);
const array2Flat = [].concat(...array2);

const matchingValue = array1Flat.filter((value) => array2Flat.includes(value));

console.log(matchingValue);

You don't need to use .flat() you can simply use concat and spread to flatten the array.

Nicolae Maties
  • 2,476
  • 1
  • 16
  • 26