Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138134

How to find the common words between 2 strings and return those sorted [duplicate]

$
0
0

I'm trying to resolve a dilemma in Javascript. I would like to find the common words between 2 strings. For example, I have the next strings "hello, world", "hello, earth" and the common word is "hello" and also "one,two,three", "four,five,one,two,six,three" ==> "one,three,two"

I tried to use thee for loop but not in a classic way but I got issues and I 'm printing the wrong result.

const commonWords = (a, b) => {
  const w = [];

  const first = a.split(",");
  const second = b.split(",");

  for (let c in first) {
    if (second, c.length >= 1) {
      w.push(c);
      w.sort();
    }
  }

  return (w);
};

console.log(commonWords("hello,world", "hello,earth"));

I would like to understand if my approach is good or there is the best way of doing it


Viewing all articles
Browse latest Browse all 138134

Trending Articles