Delete elements in first string which are not in second string in JavaScript

The problem statement asks us to delete elements from the first string that are not present in the second string. In other words, we need to keep only the characters from the first string that also exist in the second string, while preserving their original order.

This problem can be viewed as finding the intersection of characters between two strings and returning a filtered version of the first string containing only common characters.

What is a Map in JavaScript?

We'll use a Map data structure to efficiently solve this problem. A Map is a collection of key-value pairs where both keys and values can be of any data type. It provides fast lookup operations for checking element existence.

let colorMap = new Map([
    ["Red", 2],
    ["Blue", 3],
    ["Yellow", 5]
]);

console.log(colorMap);
Map(3) { 'Red' => 2, 'Blue' => 3, 'Yellow' => 5 }

Algorithm

Step 1 ? Create a function that takes two strings as input parameters

Step 2 ? Split both strings into character arrays using the split method

Step 3 ? Create a Map to store characters from the second string for fast lookup

Step 4 ? Populate the Map with all characters from the second string

Step 5 ? Filter the first string's characters, keeping only those present in the Map

Step 6 ? Join the filtered characters back into a string and return the result

Example

function deleteUncommonElements(str1, str2) {
    // Split strings into character arrays
    let charArray1 = str1.split('');
    let charArray2 = str2.split('');
    
    // Create a map to store characters from second string
    const charMap = {};
    
    // Add all characters from second string to map
    charArray2.forEach(char => {
        charMap[char] = 1;
    });
    
    // Filter first string to keep only common characters
    let filteredArray = charArray1.filter(char => {
        return charMap.hasOwnProperty(char);
    });
    
    // Join and return the result
    return filteredArray.join('');
}

const str1 = 'abcdefgh';
const str2 = 'bananana';

const result = deleteUncommonElements(str1, str2);
console.log("Original string 1:", str1);
console.log("Original string 2:", str2);
console.log("Filtered result:", result);
Original string 1: abcdefgh
Original string 2: bananana
Filtered result: ab

Using Set for Cleaner Code

We can also use a Set data structure for a more concise solution:

function deleteUncommonElementsWithSet(str1, str2) {
    const charSet = new Set(str2.split(''));
    
    return str1
        .split('')
        .filter(char => charSet.has(char))
        .join('');
}

const str1 = 'programming';
const str2 = 'gram';

const result = deleteUncommonElementsWithSet(str1, str2);
console.log("Result:", result);
Result: rgrm

Time and Space Complexity

Time Complexity: O(n + m) where n is the length of the first string and m is the length of the second string. We traverse both strings once.

Space Complexity: O(m) for storing unique characters from the second string in the Map or Set.

Conclusion

This approach efficiently solves the problem using JavaScript's built-in methods and data structures. The Map/Set provides O(1) lookup time, making the overall solution optimal for filtering common characters between two strings.

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

217 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements