Similarities between different strings in JavaScript

In JavaScript, finding similarities (intersections) between two arrays of strings is a common operation. We need to write a function that computes the intersection of two string arrays and returns elements that appear in both arrays.

Problem Statement

Given two arrays of strings, find the common elements that exist in both arrays. Each element in the result should appear as many times as it shows in both arrays.

Example

If we have these input arrays:

arr1 = ['hello', 'world', 'how', 'are', 'you'];
arr2 = ['hey', 'world', 'can', 'you', 'rotate'];

The expected output should be:

['world', 'you']

Approach

For unsorted arrays, we'll iterate through the smaller array and check if each element exists in the larger array. When a match is found, we add it to the result and mark it as used to handle duplicates correctly. This approach has O(n²) time complexity but is straightforward to implement.

Implementation

const arr1 = ['hello', 'world', 'how', 'are', 'you'];
const arr2 = ['hey', 'world', 'can', 'you', 'rotate'];

const intersectElements = (arr1, arr2) => {
    const res = [];
    const { length: len1 } = arr1;
    const { length: len2 } = arr2;
    const smaller = (len1 = len2 ? arr1 : arr2).slice();
    
    for(let i = 0; i 

[ 'world', 'you' ]

How It Works

The algorithm works by:

  • Creating copies of both arrays to avoid modifying originals
  • Identifying the smaller and larger arrays for optimization
  • Iterating through the smaller array
  • For each element, checking if it exists in the larger array using indexOf()
  • If found, adding it to the result and replacing it with undefined to handle duplicates

Alternative Approach Using Set

For better performance with large arrays, you can use a Set-based approach:

const intersectWithSet = (arr1, arr2) => {
    const set1 = new Set(arr1);
    return arr2.filter(item => set1.has(item));
};

const arr1 = ['hello', 'world', 'how', 'are', 'you'];
const arr2 = ['hey', 'world', 'can', 'you', 'rotate'];

console.log(intersectWithSet(arr1, arr2));
[ 'world', 'you' ]

Conclusion

Both approaches effectively find string similarities between arrays. The first method handles duplicates properly, while the Set-based approach offers better performance for large datasets. Choose based on your specific requirements for duplicate handling and performance needs.

Updated on: 2026-03-15T23:19:00+05:30

188 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements