Define a function that takes an array of strings, and returns the most commonly occurring string that array.

node v10.16.3
version: 1.0.0
endpointsharetweet
let stringList = ['Hello', 'Hello', 'Bye', 'Joe', 'Run', 'Flame', 'Joe', 'Joe', 'Toe', 'Run', 'Hello', 'Hello'] let mostCommonString = function(stringList){ // Using a map instead of an object as Maps are iterable let wordCount = new Map(); // Insert the word as a key, and the occurence count as a value for(let i = 0; i < stringList.length; i++){ let currentWord = stringList[i] let currentWordCount = wordCount.get(stringList[i]) if (currentWordCount != undefined){ wordCount.set(currentWord, currentWordCount += 1) } else { wordCount.set(currentWord, 1)} } let mostCommonWord = undefined; let mostCommonWordCount = 0; // Determine which word has the highest value. If two have the same amount, it will return the latest word for(let [key,value] of wordCount){ if(value > mostCommonWordCount){ mostCommonWord = key; mostCommonWordCount = value; } } return mostCommonWord; } console.log(mostCommonString(stringList))
Loading…

no comments

    sign in to comment