Open In App

How to find if two arrays contain any common item in Javascript ?

Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript Array is a single variable that is used to store elements of different data types. JavaScript arrays are zero-indexed. So, we are given two arrays containing array elements and the task is to check if two arrays contain any common elements then it returns True otherwise returns False.

These are the following ways to solve this problem:

Examples:

Input: array1 = ['a', 'b', 'c', 'd', 'e']
            array2 = ['f', 'g', 'c']
Output: true
Input: array1 = ['x', 'y', 'w', 'z']
           array2 = ['m', 'n', 'k']
Output: false

Method 1: Brute Force approach using JavaScript loops

  • Compare each and every item from the first array to each and every item of the second array.
  • Loop through array1 and iterate it from beginning to end.
  • Loop through array2 and iterate it from beginning to end.
  • Compare each and every item from array1 to array2 and if it finds any common item then return true otherwise return false.

Example: In this example, we will be using the above approach to find if two arrays contain any common item in Javascript.

javascript
// Declare two array
let array1 = ['a', 'b', 'c', 'd'];
let array2 = ['k', 'x', 'z'];

// Function definition with passing two arrays
function findCommonElement(array1, array2) {

    // Loop for array1
    for (let i = 0; i < array1.length; i++) {

        // Loop for array2
        for (let j = 0; j < array2.length; j++) {

            // Compare the element of each and
            // every element from both of the
            // arrays
            if (array1[i] === array2[j]) {

                // Return if common element found
                return true;
            }
        }
    }

    // Return if no common element exist
    return false;
}

console.log(findCommonElement(array1, array2))

Output
false

Method 2: Creating a new JavaScript Object

  • Create an empty object and loop through the first array.
  • Check if the elements from the first array exist in the object or not. If it doesn’t exist then assign properties === elements in the array.
  • Loop through the second array and check if elements in the second array exist on created object.
  • If an element exists then return true else return false.

Example: In this example, we will be using the above approach to find if two arrays contain any common item in Javascript.

javascript
// Declare Two array
let array1 = ['a', 'd', 'm', 'x'];
let array2 = ['p', 'y', 'k'];

// Function call
function findCommonElements2(arr1, arr2) {

    // Create an empty object
    let obj = {};

    // Loop through the first array
    for (let i = 0; i < arr1.length; i++) {

        // Check if element from first array
        // already exist in object or not
        if (!obj[arr1[i]]) {

            // If it doesn't exist assign the
            // properties equals to the 
            // elements in the array
            let element = arr1[i];
            obj[element] = true;
        }
    }

    // Loop through the second array
    for (let j = 0; j < arr2.length; j++) {

        // Check elements from second array exist
        // in the created object or not
        if (obj[arr2[j]]) {
            return true;
        }
    }
    return false;
}

console.log(findCommonElements2(array1, array2))

Output
false

Method 3: Using filter method

  • JavaScript Array filter() Method is used to create a new array from a given array consisting of only those elements from the given array that satisfy a condition set by the argument method.
  • In this approach, we will create a Set using the first array to store unique items.
  • Filter common items by using the filter method on the second array, checking against the Set.
  • Return true if the filtered array is not empty, indicating the presence of common items; otherwise, return false.

Example: In this example, we have used filter method to to check if two arrays contain any common items.

Javascript
function haveCommonItems(arr1, arr2) {
  const set1 = new Set(arr1);
  const commonItems = arr2.filter(item => set1.has(item));
  return commonItems.length > 0;
}

// Example usage
const array1 = [1, 2, 3, 4, 5];
const array2 = [5, 6, 7, 8, 9];
const result = haveCommonItems(array1, array2);
console.log(result); // Output: true

Output
true

Method 4: Using JavaScript Array.some() method

The JavaScript Array.some() method tests whether at least one element in the array satisfies the provided function. It returns true if, for at least one element, the callback function returns true; otherwise, it returns false.

Syntax:

arr.some(callback(element, index, array), thisArg)

Example: In this example, we’ll utilize the Array.some() method to find if two arrays contain any common items.

JavaScript
function haveCommonItems(arr1, arr2) {
  return arr1.some(item => arr2.includes(item));
}
 
// Example usage
const array1 = ['a', 'b', 'c', 'd', 'e'];
const array2 = ['f', 'g', 'c'];
const result = haveCommonItems(array1, array2);
console.log(result); // Output: true

Output
true

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



Last Updated : 28 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads