Finding matches in two elements JavaScript

We are required to write a function that returns true if the string in the first element of the array contains all of the letters of the string in the second element of the array.

For example:

["hello", "Hello"], should return true because all of the letters in the second string are present
in the first, ignoring their case.

The arguments ["hello", "hey"] should return false because the string "hello" does not contain a "y".

Lastly, ["Alien", "line"], should return true because all of the letters in "line" are present in "Alien".

This is a fairly simple problem; we will just split the second element of the array and iterate over the array thus produced to check whether the first element contains all the characters or not.

Example

const arrayContains = ([first, second]) => {
    return second
        .toLowerCase()
        .split("")
        .every(char => {
            return first.toLowerCase().includes(char);
        });
};

console.log(arrayContains(['hello', 'HELLO']));
console.log(arrayContains(['hello', 'hey']));
console.log(arrayContains(['Alien', 'line']));

Output

The output in the console will be:

true
false
true

How It Works

The function uses array destructuring to extract the first and second strings from the input array. It then:

  • Converts the second string to lowercase for case-insensitive comparison
  • Splits it into individual characters using split("")
  • Uses every() to check if all characters exist in the first string
  • The includes() method checks if each character is present in the lowercase first string

Alternative Approach Using Set

For better performance with longer strings, you can use a Set to store characters from the first string:

const arrayContainsSet = ([first, second]) => {
    const firstChars = new Set(first.toLowerCase().split(""));
    return second
        .toLowerCase()
        .split("")
        .every(char => firstChars.has(char));
};

console.log(arrayContainsSet(['Programming', 'gram']));
console.log(arrayContainsSet(['JavaScript', 'Python']));
true
false

Conclusion

The every() method combined with includes() provides an elegant solution for checking if one string contains all characters of another. For performance optimization with larger strings, consider using a Set-based approach.

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

250 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements