You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取两个字符串中的不匹配单词?现有代码问题求助

Fixing the Unmatched Words Finder Code

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) where words1[i] is a single word (like "world") and el is an element from myArray. 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

  1. Normalize Case: We convert both strings to lowercase first so words like "World" and "world" are treated as matches.
  2. Filter Unmatched Words:
    • onlyInStr1 uses filter() to keep words from words1 that don’t exist in words2.
    • onlyInStr2 does the reverse for words in words2 not found in words1.
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:59:31