如何获取两个字符串中的不匹配单词?现有代码问题求助
Hey Sara, let's get this sorted out! The core issue with your current code is that you're trying to use includes() on a single string (words1[i]) instead of checking if a word exists in the opposite array. Plus, the nested loops and filter logic are tangled up, leading to errors and incorrect results. Let's break down how to fix this properly.
What's Wrong with the Original Code?
- You’re using
words1[i].includes(el)wherewords1[i]is a single word (like "world") andelis an element frommyArray. This checks if one word contains another, not if the word exists in the other array—totally not what you need. - The nested loops trigger the filter multiple times inside iterations, which would output messy, repeated results instead of a clean final array of unmatched words.
Solution Code
Here's a straightforward approach to get all unmatched words between the two strings:
var str1 = "world is beautiful"; var str2 = "is world bautiful"; // Convert both strings to lowercase word arrays to ignore case differences const words1 = str1.toLowerCase().split(/\s+/); const words2 = str2.toLowerCase().split(/\s+/); // Find words in str1 that aren't present in str2 const onlyInStr1 = words1.filter(word => !words2.includes(word)); // Find words in str2 that aren't present in str1 const onlyInStr2 = words2.filter(word => !words1.includes(word)); // Combine both arrays to get all unmatched words from either string const unmatchedWords = [...onlyInStr1, ...onlyInStr2]; console.log(unmatchedWords); // Output: ["beautiful", "bautiful"]
If you specifically want only the words from str1 that aren’t in str2 (matching your expected ["beautiful"]), just use onlyInStr1 instead of combining both arrays.
How This Works
- Normalize Case: We convert both strings to lowercase first so words like "World" and "world" are treated as matches.
- Filter Unmatched Words:
onlyInStr1usesfilter()to keep words fromwords1that don’t exist inwords2.onlyInStr2does the reverse for words inwords2not found inwords1.
- Combine Results: Using the spread operator (
...), we merge both arrays to get all unmatched words from either string.
Alternative: Using Sets for Better Performance
If you’re working with large strings, using Set will make lookups faster (O(1) instead of O(n)):
const set1 = new Set(words1); const set2 = new Set(words2); const onlyInStr1 = words1.filter(word => !set2.has(word)); const onlyInStr2 = words2.filter(word => !set1.has(word)); const unmatchedWords = [...onlyInStr1, ...onlyInStr2];
This works exactly the same but is more efficient for larger datasets.
内容的提问来源于stack exchange,提问作者Sara Ree

