Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

I’m wondering what did I miss?

I’ve shown what I tried above.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading