This question already has answers here:
Simplest code for array intersection in javascript
                            
                                (49个答案)
                            
                    
                3个月前关闭。
        

    

我正在尝试解决Javascript中的难题。我想找到2个字符串之间的常用词。例如,我有下一个字符串"hello, world", "hello, earth",常用词是"hello",还有"one,two,three", "four,five,one,two,six,three" ==> "one,three,two"

我尝试将您用于循环,但不是以经典的方式使用,但是遇到了问题,并且打印了错误的结果。

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"));


我想了解我的方法是好的还是最好的方法

最佳答案

const commonWords = (a, b) => {
let w;
let first = a.split(",");
let second = b.split(",");
let temp;

if (second.length > first.length) {temp = second; second = first; first = temp;}
w =  first.filter(function (e) {
    return second.indexOf(e) > -1;
});

return w.sort();
};

console.log(commonWords("one,two,three", "four,five,one,two,six,three"));



  [“一个”,“三个”,“两个”]

关于javascript - 如何找到2个字符串之间的常见单词并返回排序后的单词,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60308690/

10-13 00:56