Reputation: 5
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.
Upvotes: 0
Views: 123
Reputation: 24342
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
Upvotes: 1
Reputation: 3749
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);
Upvotes: 3