简体   繁体   中英

javascript remove repeated words from array element

Given an array:

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

A javascript code is needed to remove all words in each element which are present in ALL of the other elements of the array and be unique so that no elements are repeated in the results., so the wanted result would be:

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

Any suggestion on an efficient solution? thx

edit
My options are:
1) convert each element to an array and use some underscore magic.
2) concat 2 elements at a time and remove duplicate words.
3) loop with in a loop and pull my hair...

Maybe there is a way to do this without iterating through the array twice, but if there is, it's beyond me. This seems to be adequate:

 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(", ")) 

Might not be the optimal solution. But this will do the job.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM