2016-10-18 5 views
2

Я хочу получить программу javascript, которая подсчитывает слово и возвращает слово и количество раз, которое появляется, например {hello: 2, "@hello": 1, world : 1, ToString: 1}Подсчитывать слова в javascript и вставлять их в объект

ниже мой код, но я только получить общее количество слов

function words(str) { 
    app = {}; 
    return str.split(" ").length; 
} 

console.log(words("hello world")); 
+1

Возможный дубликат [JavaScript группы массивом] (HTTP://stackoverflow.com/questions/12873228/javascript-group-by-array) – Andreas

ответ

7

Использование уменьшить итерировать слова массива, и сосчитать экземпляров:

function words(str) { 
 
    return str.split(" ").reduce(function(count, word) { 
 
     count[word] = count.hasOwnProperty(word) ? count[word] + 1 : 1; 
 
     
 
     return count; 
 
    }, {}); 
 
} 
 

 
console.log(words("reserved words like prototype and toString ok? Yes toString is fine"));

+0

Очень элегантный, мне он нравится. – ReSpawN

+0

если я передаю toString, он дает ошибку, например, native function toString() – Iakhator

+0

Можете ли вы добавить код, который используете? –

0
function words(str){ 


    var words = []; 

    //check if words list is empty if so then insert the first word into the array 


    if(!words.length){ 
     var word = str.split(" ")[0]; 
     words.push({"word":word, "occurences":1}); 
    } 

    //convert string to array so you can iterate through it 
    str = str.split(" "); 

    //iterate through the array starting from the first position because word at the position 0 is already in the array 
    for(var i = 1; i<str.length; i++){ 

     //iterate through the words list to the see if the word has appeared yet 
     var wordExists = false; 

     for(var j = 0; j<words.length; j++){ 
      if(str[i] == words[j].word){ 

       //word exists in word so count one up 
       words[j].occurences += 1; 

       //used to prevent the word from being inserted twice 
       wordExists = true; 
       break; 
      } 
     } 

     //insert new word in words if it 
     if(!wordExists){ 
      words.push({"word":str[i], "occurences":1}); 
     } 
    } 
    return words; 
} 
0

Это код, и то, что я прошел через @ori

function words(str) { 
    var adjustedStr = str.replace(/\n|\t|\s\s+/g, ' '); 
    return adjustedStr.split(' ').reduce(function(count, word) { 
    count[word] = (count[word] || 0) + 1; 

    return count; 
    }, {}); 
} 

console.log(words("reserved words like prototype and toString ok?")); 

он утешал из

{toString: "function toString() { [native code] }1"} 
+0

Проверка hasOwnProperty, как и принятое отображение ответа. Но я также сделал один из них: вы создаете более простой литерал объекта, используя нулевой конструктор. – Keith

0

Чтобы зарезервированные слова в литералов объектов без использования hasOwnerProperty, вы может использовать конструктор нулей для объекта.

например.

function words(str) { 
 
    var adjustedStr = str.replace(/\n|\t|\s\s+/g, ' '); 
 
    return adjustedStr.split(' ').reduce(function(count, word) { 
 
     count[word] = (count[word] || 0) + 1; 
 
     return count; 
 
    }, Object.create(null)); 
 
} 
 

 
console.log(words("reserved words like prototype and toString ok?"));

0

ES6 подход, который уменьшает над массивом элементов, таких как строки и возвращает количество:

const strFrequency = function (stringArr) { 
    return stringArr.reduce((count, word) => { 
     count[word] = (count[word] || 0) + 1; 
     return count; 
    }, {}) 
} 

let names = ["Bob", "Bill", "Bo", "Ben", "Bob", "Brett", "Ben", "Bill", "Bo", "Ben", "Bob", "Ben"]; 

console.log(strFrequency(names)); 
// => {Bob: 3, Bill: 2, Bo: 2, Ben: 4, Brett: 1}