如何从一个长字符串中过滤唯一单词?

时间:2019-04-23 15:04:10

标签: arrays sorting filter split unique

我需要有关家庭作业的帮助:我需要从lorem ipsum文本中过滤所有唯一单词,并从所有唯一单词中构建new Array。

我尝试过滤唯一文字的文本: 'Lorem ipsum dolor坐得很近,自学成才。 Eius velit doloremque iusto inciunt,耳um Rerum maxime eum,porro mollitia,labour numquam,laboriosam possimus ipsam sapiente ullam deserunt。 我目前所做的事情,不确定是否很好:

var listOf = 'STRING OF LONG TEXTS';
var newAr = listOf.toLowerCase().replace('.','').replace('?','').replace(',','').split(' ');
function renderWords ( data ) {
    var unique = [];
    if ( !Array.isArray(data) || data.length === 0 ){
        return HTML;
    }
    for ( var i=0; i<data.length; i++ ) {
        if ( unique.indexOf( data[i] ) === -1 ){

            unique.push(data[i]);
            console.log(unique);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

you can store the words in a map of string, int So first you are getting all words, that should be not that hard if you are looking for whitespaces and after that you store every single word in that map and set the counter to one and if it already exist, than you increase your counter. At the end you go over your map and check for values == 1 and store them in an array