0

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?

rlpool06
  • 3
  • 1
  • Is `array2` a function? You're calling it as such. But you seem to be searching for the *element* of array1 as an *index* of array2 and returning that. – mykaf Oct 18 '22 at 19:05

4 Answers4

0

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)
IT goldman
  • 14,885
  • 2
  • 14
  • 28
0

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

const filteredIdArray = array1.filter((item) => array2.includes(item))
  • short syntax. less efficient than "1 pass" algorithm – IT goldman Oct 18 '22 at 18:55
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 21 '22 at 01:54
0

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)]

danh
  • 62,181
  • 10
  • 95
  • 136
0

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 );
PeterKA
  • 24,158
  • 5
  • 26
  • 48