JSFiddle - React, Tailwind, and code Playground
by Prathameshsb
JavaScript
function findWordsWithLetters(words, targetWord) {
// Helper function to check if a word contains the letters of the target word
function hasSameLetters(word, targetWord) {
const wordMap = new Map();
// Count the occurrences of each letter in the word
for (const letter of word) {
wordMap.set(letter, (wordMap.get(letter) || 0) + 1);
}
// Check if the word has the same letters as the target word
for (const letter of targetWord) {
if (!wordMap.has(letter) || wordMap.get(letter) === 0) {
return false;
}
wordMap.set(letter, wordMap.get(letter) - 1);
}
return true;
}
// Filter words based on the condition
const result = words.filter(word => hasSameLetters(word, targetWord));
return result;
}
// Example usage:
const wordsArray = ['albert', 'catty', 'david', 'donald', 'nonono', 'dad', 'add'];
const targetWord = 'dad';
const resultArray = findWordsWithLetters(wordsArray, targetWord);
console.log(resultArray);