DEV Community

Discussion on: How to Get the Intersection of Two Arrays

Collapse
 
realdolos profile image
Dolores Greatamsky

The Set solution is not equivalent due to the filtered result being put through another Set, eliminating duplicates, while the plain filter+includes solution will return duplicates from the first array.

The indexOf solution shouldn't (ab)use an object as a hash map, and then parseInt, really, pretty please. People might copy that code, especially as it is last in your article.

My general purpose solution would be:

/**
 * Return elements present in both arrays, without duplicates
 */
function intersectWith(arr, other) {
  const known = new Set(arr);
  return other.filter(function(e) {
    if (!known.has(e)) {
      return false;
    }
    known.delete(e); // Avoid duplicates. Remove line if you want duplicates from other.
    return true;
  });
}

I like to avoid the conversation from array to another array (with filter) to a Set and back to array again 😁