Most JavaScript programmers face difficulty to find common elements in two arrays in JavaScript (JS); if you are one of them, don’t worry and keep reading this article. 🕵️
An array is a subscripted variable that can store multiple values; we can access all its elements with the help of an index number. To find common elements in two arrays, we have different methods and discuss them in detail. You will also find the most suitable and easy-to-understand examples in this article.
Before diving straight, let’s just understand the concept of an array and the method of accessing elements.
Table of Contents
What is an Array in JavaScript?
An array is a special variable that can hold multiple values of the same or different type. For example, in JavaScript, we can store numbers, strings, or any other data type in a single array. To access different elements of an array, we use an index number that always starts from 0.
Let’s quickly go through an example in which we declare and manipulate an array:
Code
// Declare and initialize an array let myarray=[20, 30, 50]; // Mostly, we use a loop for accessing elements for (let index=0; index<3; index++) console.log("Array[",index,"]=",myarray[index]);
Output
Array[ 0 ]= 20 Array[ 1 ]= 30 Array[ 2 ]= 50
Different Ways to Find Common Elements in Two Arrays in JavaScript
We can find common elements in two arrays in JavaScript with the help of these four ways:
- Using the intersection method.
- Using filter and includes methods.
- Using nested loop.
- Using the while loop and sort method.
Now we will see the details of each method and explanation with the help of simple examples.
Method 1: Using the Intersection Method
We can find common elements in two arrays with the help of the intersection method of the library Underscore or Lodash. Let’s understand this method with the help of this code:
Code
// we have to download the underscore module to use the intersection method let _ = require('underscore'); console.log("Example of intersection method"); // Declare and initialize two arrays let myarray1=[20, 30, 50]; let myarray2=[10, 20, 30, 40]; // use intersection method to get common elements console.log("Common Elements are:", _.intersection(myarray1, myarray2));
Output
Example of intersection method Common Elements are: [20, 30]
Method 2: Using Filter and Includes Methods
The filter method creates an array with the elements that pass a provided test. This method does not change the original elements of an array. On the other hand, we use the includes method with the filter method to check whether the current element is in the given array. You will understand this method with the help of an example:
Code
console.log("Example of filter and includes methods"); //Declare and initialize two arrays let myarray1 = [10, 20, 30, 40, 50, 60]; let myarray2 = [20, 40, 70]; //Use filter and includes methods to get common elements let commonElements = myarray1.filter(value => myarray2.includes(value)); console.log("Common elements of both arrays:",commonElements);
Output
Example of filter and includes methods Common elements of both arrays: [ 20, 40 ]
Method 3: Using the Nested loop
In this method, we use a loop inside another outer loop used for an array and an inner loop used for another array. We have to use the if structure to compare both arrays; if elements are common, we will push them into another array.
Now let’s understand this method with the help of this simple example:
Code
console.log("Example of nested loop"); // Declare and initialize arrays a and b let a=[0, 20, 30, 40, 50, 60]; let b=[20, 40, 60, 70, 80]; let c=[]; // Outter loop for array a for(let i=0 ; i<a.length ; i++) { // Inner loop for array b for(let j=0 ; j<b.length ; j++) { //compare each element of array a with all the elements of array b if(a[i] == b[j]) { // if there is any common element, push it into another array c.push(a[i]); } } } console.log("Common Elements are:",c);
Output
Example of nested loop Common Elements are: [ 20, 40, 60 ]
Method 4: Using While Loop and Sort Method
In this method, first of all, we will sort both arrays and then use a while loop to find common elements of both arrays. It is better to explain this method with the help of an example:
Code
console.log("Example of while loop and sort method"); // Declare and initialize arrays a and b let a=[20, 10, 60, 40, 50, 30]; let b=[80, 40, 60, 20, 70]; // An array to store common elements let c=[]; // Sort both arrays a.sort(); b.sort(); // i and j are the index of arrays a and b let i = 0, j = 0; // if pointers greater than the length of any one array // then come out of the while loop while(i<a.length && j<b.length) { // if found any common element then store it in array c if(a[i] == b[j]) { c.push(a[i]); // increase index of both arrays in case of found common element i++; j++; } // increase the index of a smaller array element else if(a[i] < b[j]) { i++; } else { j++; } } console.log("Common Elements are:",c);
Output
Example of while loop and sort method Common Elements are: [ 20, 40, 60 ]
Conclusion
This article discussed four ways to find common elements in two arrays. All the methods are easy and valuable, but we found the intersection and filter methods and easy. It depends on our requirements which way will work for us. If we want to create our own function to compare two arrays, then the nested loop and while loop method will work best. On the other hand, if the speed of the code execution matters, then we will pick intersection or filter methods.
Let’s have a quick review of the topics discussed in this article.
- What is an array in JavaScript?
- Ways to find common elements in two arrays.
- How do we use intersection methods?
- How do we use filter and includes methods?
- How do we use a nested loop to find common elements?
- How do we use the while loop and sorted method to find common elements?
Hopefully, you’ve found the above solutions helpful. If you have any questions regarding these, let us know below 👇, and we will love to assist you.
Happy coding!