Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

Today, I’m going to show you how do I find common elements in two arrays of javascript, here I will use javascript filter() to iterate the array and return a new array based on condition, and includes() to check string is available in an array or not.

  • The filter() method creates a new array with all elements that pass the test implemented by the provided function.

  • The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

Well, let’s start today’s topic How to find common elements in two arrays javascript?

Okay, let’s plan what we are going to do in code.

  1. Create sample array variables.
  2. To get common elements in new array use the filter() method
  3. Use the includes() method to check string is available in arrays
// Create sample arrays variables.
const domainsArr1 = ["infinitbility", "aGuideHub", "SortoutCode"];
const domainsArr2 = ["notebility", "aGuideHub", "repairbility"];

// To get common elements in new array use `filter()` method
// Use `includes()` method to check string is available in array
const filteredArray = domainsArr1.filter(value => domainsArr2.includes(value));

console.log("filteredArray", filteredArray)
// Expected 'filteredArray' [ 'aGuideHub' ]

In the above example I used filter() and includes() both methods to create a new array of matched elements.

Here, as per expectaion it should show 'filteredArray' [ 'aGuideHub' ].

let’s check the output.

javascript, find common elements in two arrays example
javascript, find common elements in two arrays example

I hope it’s help you, All the best 👍.