Home > Enterprise >  Compare two arrays of integers and return an array with all matches
Compare two arrays of integers and return an array with all matches

Time:10-19

I currently have two arrays with a bunch of ids. I want to compare the two arrays to see what ids match, then return an array with only the matching ids. I've tried multiple approaches, but nothing seems to work so far. This is what I've done:

const filteredIdArray = array1.filter((item) =>
    array2(item)
  );



const filteredIdArray = array1.filter(
    (item) => array2.indexOf(item) !== -1
  );

Both attempts were pulled from other examples, and neither is working. I did make sure that my array1 and array2 were actually arrays not objects. Is there something I'm missing here?

CodePudding user response:

I think in the first approach it should be array2.includes.

const filteredIdArray = array1.filter((item) => array2.includes(item))

CodePudding user response:

Use a intermediate hash object to hold id's as its key. That would make it easier to find "duplicates" and push to a result.

arr1 = [1, 2, 3, 4, 0]
arr2 = [3, 4, 5, 6, 0]

result = []
hash = {}

arr1.forEach(item => hash[item] = true)
arr2.forEach(item => hash[item] === true && result.push(item))

console.log(result)

CodePudding user response:

Rephrasing, this is array intersection. A terse, readable, quick (1 pass through each array) is (sort of like this)...

const intersect = (a, b) => {
  const setB = new Set(b);
  return a.filter(el => setB.has(el));
}

console.log(intersect([1,2,3,4], [3,4,5,6]))

There's ambiguity in the question about whether we're aiming for unique matches. This idea returns all matches, including duplicates. To eliminate those, run the result through a set once more. [...new Set(resultWithDups)]

CodePudding user response:

You can use Array#filter and Array#includes methods as follows:

const 
    arr1 = [2,5,6,8,9,10],
    arr2 = [3,4,7,6,8,11],
    
    output = arr1.filter(n => arr2.includes(n));
    
    console.log( output );

Also .....

Your second option should work:

const 
    arr1 = [2,5,6,8,9,10],
    arr2 = [3,4,7,6,8,11],
    
    output = arr1.filter(n => arr2.indexOf(n) !== -1);
    
    console.log( output );

  • Related