Професионална програма
Loading...
+ Нов въпрос
amydarling avatar amydarling 13 Точки

6. Word Occurrences - Associative Arrays JavaScript Fundamentals

Здравейте ,имам проблем с тази задача и не мога да си видя грешката . Ето и моето решение и условието :  https://pastebin.com/mD33vXHx

1.Word Occurrences

Write a function that counts the times each word occurs in a text. Print the words sorted by count in descending order. The input comes as an array of strings.

Example

Input

Output

["Here", "is", "the", "first", "sentence", "Here", "is", "another", "sentence", "And", "finally", "the", "third", "sentence"]

sentence -> 3 times

Here -> 2 times

is -> 2 times

the -> 2 times

first -> 1 times

another -> 1 times

And -> 1 times

finally -> 1 times

third -> 1 times

Hint

  • Create a map
  • Loop through the elements of the array of words
  • Update the map
  • Sort the map by value in descending:

6.	Word Occurrences - Associative Arrays JavaScript Fundamentals

  • Finally, print the result in format as the example above
Тагове:
0
Fundamentals Module
amydarling avatar amydarling 13 Точки

Благодаря!

1
MartinBG avatar MartinBG 3751 Точки

Имаше грешка при броенето на думите и във форматирането на изхода.

Оправеното решение:

function wordOccurrences(arr){
    let map = new Map ();
 
    for(let word of arr){
        let wordOccurrences = 1;
 
        if(map.has(word)){
            wordOccurrences += map.get(word);
        }
      
        map.set(word, wordOccurrences)
    }
  
    let sorted = Array.from(map);
    sorted.sort((a,b) => b[1] - a[1])
 
    for(let [word,words] of sorted){
        console.log((`${word} -> ${words} times`));
    } 
}

 

0
amydarling avatar amydarling 13 Точки

Благодаря!

1