How to find if two arrays contain a common item in Javascript
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 arrayslet colors1 = ["yellow", "orange", "red"]let colors2 = ["white", "black","purple", "red", "green"]//function to check for common elementsfunction checkForCommon(colors1,colors2){//outer loop travere the first array colors1for(let i=0; i<colors1.length; i++){//inner loop travere the second array colors2for(let j=0; j<colors2.length; j++){//check if present element of colors1 is equal to present element of colors2if(colors1[i] == colors2[j]){return true;}}}//returns false if no common elements foundreturn false;}//call the function and print the resultconsole.log(checkForCommon(colors1,colors2))
Explanation
In the code snippet above:
- In lines 2 and 3, we declare and assign two arrays,
colors1andcolors2. - In line 6, we define a function
checkForCommonthat accepts two arrays as parameters. - In line 9, we use the outer
forloop to traverse the first array,colors1. - In line 12, we use the inner
forloop to traverse the second array,colors2. - In line 15, we check if the current element of array
colors1is equal to the current element of arraycolors2.- If they are equal, return
true. - If they are not equal, continue with the loop.
- Return
falseif no common element is found in the arrays.
- If they are equal, return
- In line 27, we call the
checkForCommonfunction and pass both arrays as parameters, and print the returned value to the console.