我正在尝试解决 Javascript 中的一个困境。我想找到两个字符串之间的共同词。例如,我有下一个字符串 "hello, world", "hello, earth"
常用词是"hello"
还有"one,two,three", "four,five,one,two,six,three" ==> "one,three,two"
我尝试使用 for 循环,但不是以经典方式,但我遇到了问题,并且打印了错误的结果。
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"));
["one", "three", "two"]
关于javascript - 如何找到两个字符串之间的共同单词并返回排序后的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60308690/