What are other methods to find intersections?

Here are a few alternative methods to find intersections between two arrays in JavaScript:

1. Using filter and includes

You can use the filter method along with includes to find common elements:

const intersection = (arr1, arr2) => {
  return arr1.filter(elem => arr2.includes(elem));
};

2. Using reduce

You can also use the reduce method to accumulate the intersection:

const intersection = (arr1, arr2) => {
  return arr1.reduce((acc, elem) => {
    if (arr2.includes(elem) && !acc.includes(elem)) {
      acc.push(elem);
    }
    return acc;
  }, []);
};

3. Using forEach

Another approach is to use forEach to iterate through one array and check for existence in the other:

const intersection = (arr1, arr2) => {
  const result = [];
  arr1.forEach(elem => {
    if (arr2.includes(elem) && !result.includes(elem)) {
      result.push(elem);
    }
  });
  return result;
};

Summary

Each of these methods has its own performance characteristics, with the Set-based method generally being the most efficient for larger datasets due to faster lookups. You can choose the method that best fits your needs based on readability and performance.

0 Comments

no data
Be the first to share your comment!