How to compare two arrays to see how many same elements they have in JavaScript?

Let's say, we have two arrays, one contains the correct answer strings of some questions and one contains the answers attempted by a candidate, but somehow the arrays got shuffled and now they don't have answers in corresponding order. But we can be sure that no two questions had the same answers.

Our job now is to write a function that takes these two arrays, checks them for common elements and finds all the common elements between them and then calculates the marks percentage of the candidate based on the count of common answers.

Example

const correct = ['India', 'Japan', 56, 'Mount Everest', 'Nile', 'Neil Armstrong', 'Inception', 'Lionel Messi', 'Joe Biden', 'Vatican City'];
const answered = ['Nile', 'Neil Armstrong', 'Joe Biden', 'Mount Everest', 'Vatican City', 'Inception', 'Japan', 56, 'China', 'Cristiano Ronaldo'];

const findPercentage = (first, second) => {
    const count = first.reduce((acc, val) => {
        if(second.includes(val)){
            return ++acc;
        };
        return acc;
    }, 0);
    return (count / first.length) * 100;
};

console.log(`Candidate have scored ${findPercentage(correct, answered)}%`);

Output

Candidate have scored 80%

How It Works

The function uses reduce() to iterate through the first array and includes() to check if each element exists in the second array. When a match is found, the accumulator is incremented. Finally, the percentage is calculated by dividing the count of matches by the total length of the first array.

Alternative Approach Using filter()

const correct = ['India', 'Japan', 56, 'Mount Everest', 'Nile'];
const answered = ['Nile', 'Japan', 56, 'China', 'France'];

const findCommonElements = (arr1, arr2) => {
    return arr1.filter(element => arr2.includes(element));
};

const commonElements = findCommonElements(correct, answered);
const percentage = (commonElements.length / correct.length) * 100;

console.log('Common elements:', commonElements);
console.log(`Score: ${percentage}%`);
Common elements: ['Japan', 56, 'Nile']
Score: 60%

Comparison

Method Returns Memory Usage
Using reduce() Count only Lower
Using filter() Common elements array Higher

Conclusion

Both methods effectively find common elements between arrays. Use reduce() when you only need the count, and filter() when you need the actual common elements for further processing.

Updated on: 2026-03-15T23:18:59+05:30

458 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements