Advertisement
TZinovieva

Word Tracker JS Fundamentals

Mar 3rd, 2023
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function wordsTracker(arr) {
  2.   const wordsToFind = arr.shift().split(' ');
  3.   const wordCounts = {};
  4.  
  5.   arr.forEach(sentence => {
  6.     wordsToFind.forEach(word => {
  7.       const wordsInSentence = sentence.split(' ');
  8.       const count = wordsInSentence.reduce((acc, curr) => {
  9.         if (curr === word) {
  10.           return acc + 1;
  11.         }
  12.         return acc;
  13.       }, 0);
  14.       wordCounts[word] = (wordCounts[word] || 0) + count;
  15.     });
  16.   });
  17.  
  18.   const sortedCounts = Object.entries(wordCounts)
  19.     .sort((a, b) => b[1] - a[1]);
  20.  
  21.   const output = sortedCounts
  22.     .map(([word, count]) => `${word} - ${count}`)
  23.     .join('\n');
  24.  
  25.   console.log(output);
  26. }
  27.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement