javascript从数组元素中删除重复的单词

时间:2017-04-28 00:24:48

标签: javascript

给定一个数组:

let myArr = ['Maybe he is a student', 'He is a boy', 'a boy'];

需要一个javascript代码来删除每个元素中存在于数组的所有其他元素中的所有单词并且是唯一的,以便在结果中不重复元素。所以想要的结果将是:

return ['Maybe he is student','He is boy', 'boy']; // "a" is common thus removed

有关有效解决方案的任何建议吗? thx

修改
我的选择是:
1)将每个元素转换为数组并使用一些下划线魔法 2)一次连接2个元素并删除重复的单词 3)循环并拉我的头发......

2 个答案:

答案 0 :(得分:3)

也许有一种方法可以做到这一点,而无需遍历数组两次,但如果存在,它就超出了我。这似乎是足够的:



var myArr = ['Maybe he is a student', 'He is a boy', 'a boy', 'boy boy'];
var count = {};
for (let sentence of myArr) {
    var current = new Set(); // to keep track of duplicates in the current sentence
    for(let word of sentence.split(" ").map( x => x.toLowerCase() )) {
        if (!current.has(word)) {
            count[word] = ++count[word] || 1;
            current.add(word);
        }
    }
}
var second = [];
for (let sentence of myArr) {
    partial = sentence.split(" ").filter( x => count[x.toLowerCase()] != myArr.length );
    if (0 != partial.length) second.push(partial.join(" "));
}
console.log(second.join(", "))




答案 1 :(得分:0)

可能不是最佳解决方案。但这将完成这项工作。

let myArr = ['Maybe he is a student', 'He is a boy', 'a boy'];
    
const t = myArr.reduce(function(a, c){
  a = a || {};
  c.split(' ').forEach(function(i){
    a[i.toLowerCase()] = a[i.toLowerCase()] ? a[i.toLowerCase()] + 1 : 1
  });
  return a;
}, [])
    
var result  = myArr.map(function(text){
  const arr =  text.split(' ');
  const r = arr.filter(function(item) { return t[item.toLowerCase()]===1 })
  return r.join(' ')
}).filter(function(y){ return y });
    
console.log(result);