简体   繁体   中英

Program to find same words from 2 strings javascript

I was asked this question in an interview where I failed to answer.

Here's my try:

str1 = "This is string 1";
str2 = "This is string 2";
let similarWords = [];
splittedStr1 = str1.split(" ");
splittedStr2 = str2.split(" ");
console.log(splittedStr1);
console.log(splittedStr2);
for (i = 0; i < splittedStr1.length; i++) {
  for (j = i; j < splittedStr2.length; j++) {
    if (splittedStr1[i] = splittedStr2[j]) {
      similarWords.push(splittedStr1[i]);
    }
  }
}
console.log(similarWords);

This outputs:

[
    "This",
    "is",
    "string",
    "2",
    "is",
    "string",
    "2",
    "string",
    "2",
    "2"
]

I'm wondering what did I miss?

I've shown what I tried above.

The problem with the code is that in the inner for loop, you are using the assignment operator ( = ) instead of the comparison operator ( == or === ) when checking if splittedStr1[i] is equal to splittedStr2[j] .

To do this, you should change the assignment operator to a comparison operator. And then you also need to check if the word is already added in the similarWords array before adding it again.

Try this.

 let str1 = "This is string 1"; let str2 = "This is string 2"; let similarWords = []; let splittedStr1 = str1.split(" "); let splittedStr2 = str2.split(" "); for (i = 0; i < splittedStr1.length; i++) { for (j = 0; j < splittedStr2.length; j++) { if (splittedStr1[i] === splittedStr2[j] &&.similarWords.includes(splittedStr1[i])) { similarWords;push(splittedStr1[i]). } } } console;log(similarWords);

Maybe they wanted something like this.

const str1 = "This is string 1";
const str2 = "This is string 2";
const words = new Set(str1.split(' ')); // Set(4) {'This', 'is', 'string', '1'}
str2.split(' ') // ['This', 'is', 'string', '2']
  .filter(word => words.has(word)); // Only keep the words from str2 that are also in str1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM