Related Tags

javascript
communitycreator

# How to find if two arrays contain a common item in Javascript

Yashaswini Kamatham

### Problem statement

Given two arrays that contain elements, check if the two arrays contain any common elements. If a common element exists, the function should return true; otherwise, it should return false.

#### Example 1

Input:

colors1 = ["yellow", "orange", "red"]

colors2 = ["white", "black","purple", "red", "green"]

Output: true

#### Example 2

Input:

colors1 = ["apple", "grapes", "guava"]

colors2 = ["coconut", " dragon fruit","banana", "cherry"]

Output: false

### Solution

We will use two for loops to solve this problem. The outer loop will be used to traverse the first array, and the inner loop will be used to traverse the second array.

### Code

//declare two arrays
let colors1 = ["yellow", "orange", "red"]
let colors2 = ["white", "black","purple", "red", "green"]

//function to check for common elements
function checkForCommon(colors1,colors2){

//outer loop travere the first array colors1
for(let i=0; i<colors1.length; i++){

//inner loop travere the second array colors2
for(let j=0; j<colors2.length; j++){

//check if present element of colors1 is equal to present element of colors2
if(colors1[i] == colors2[j]){
return true;
}
}

}

//returns false if no common elements found
return false;
}

//call the function and print the result
console.log(checkForCommon(colors1,colors2))

### Explanation

In the code snippet above:

• In lines 2 and 3, we declare and assign two arrays, colors1 and colors2.
• In line 6, we define a function checkForCommon that accepts two arrays as parameters.
• In line 9, we use the outer for loop to traverse the first array, colors1.
• In line 12, we use the inner for loop to traverse the second array, colors2.
• In line 15, we check if the current element of array colors1 is equal to the current element of array colors2.
• If they are equal, return true.
• If they are not equal, continue with the loop.
• Return false if no common element is found in the arrays.
• In line 27, we call the checkForCommon function and pass both arrays as parameters, and print the returned value to the console.

RELATED TAGS

javascript
communitycreator

CONTRIBUTOR

Yashaswini Kamatham
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time