Skip to content
Advertisement

Javascript Get the common elements of three arrays

I am trying to filter the common elements of 3 arrays. But instead of getting the common elements of 3 arrays, it only reads the 2 arrays and not the 3rd array. Here is my code, thank you:

function commonElementsOfArray(arr1, arr2, arr3) {
    return arr1.filter(function (n) {
        return arr2.indexOf(n) !== -1;
        return arr3.indexOf(n) !== -1;
    });
}

Advertisement

Answer

As mentioned by @Titus, the issue in your code is the double return statements – once the first return is found the filter function will exit.

However, there is also an issue worth pointing out in your approach to finding common elements regarding Array.indexOf. The problem is that Array.indexOf is an O(n) operation, meaning the parameter will be checked against every element of arr2 and every element of arr3. On face value that sounds like the right approach, but if the arrays are large then this will be a very slow function. For instance, if each array has 1,000 entries (n) then your function will take each element and compare against everything in arr2 and arr3, resulting in thousands of operations per element (O(n^2) time complexity).

One alternative is to create a Map and populate it as you iterate through each array to track the number of times an entry has been seen. Finding values now has O(1) runtime. There is still the cost of iterating through each array which yields O(n) but because of the fast lookup this becomes n * 1 operations or O(n) time complexity.

function commonElementsOfArray(...arrays) {
  const size = arrays.length;
  const map = new Map();
  
  arrays.forEach(arr => {
    arr.forEach(entry => {
      if (!map.has(entry)) {
        map.set(entry, 1);
      } else {
        let timesSeen = map.get(entry);
        map.set(entry, ++timesSeen);
      }
    });
  });

  const commonElements = [];
  map.forEach((count, key) => {
    if (count === size) {
      commonElements.push(key);
    }
  });

  return commonElements;
}

console.log(commonElementsOfArray([1, 2, 3], [1, 2, 4], [2, 4, 5]));
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement