How to find common elements in two arrays in JavaScript?

There are many ways to get the common elements of two arrays in JavaScript, some very easy and some more complex. In the short guide, we will focus on the simplest ones and we will try to do this only with a few lines of code.

How to find common elements in two arrays of strings (or numbers)?

To find common elements in two arrays of strings (or numbers), we can use a combination Array.filter method and Array.includes method. In simple words, we will filter the first array with values that the second array includes and we will return the outcome to the common variable.

const array1 = ['Dog', 'Cat', 'Cow', 'Horse', 'Goose'];
const array2 = ['Mouse', 'Chicken', 'Horse', 'Duck', 'Cat'];

const common = array1.filter(element => array2.includes(element));

How to find common elements in two arrays of objects?

Finding common elements in an array of objects is a bit more difficult. When we are sure that the order of object properties is the same, we can use JSON.stringify method to compare two objects. When objects are the same, we will push one of them to the common variable.

const array1 = [{ name: 'Tom', age: '35' }, { name: 'Natalie', age: '18' }];
const array2 = [{ name: 'Mike', age: '48' }, { name: 'Tom', age: '35' }];
const common = [];

for (const element1 of array1) {
    for (const element2 of array2) {
        if (JSON.stringify(element1) === JSON.stringify(element2)) {
            common.push(element1);
        }
    }
}

But if you can’t be sure that object properties are in the same order, you can use isEqual method from the Lodash library to compare two objects in the if statement.

const array1 = [{ name: 'Tom', age: '35' }, { name: 'Natalie', age: '18' }];
const array2 = [{ age: '48', name: 'Mike' }, { age: '35', name: 'Tom' }];
const common = [];

for (const element1 of array1) {
    for (const element2 of array2) {
        if (_.isEqual(element1, element2)) {
            common.push(element1);
        }
    }
}

Now, you are able to find common elements of two arrays in JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *