0

So I've created this JS code to get a map where every word in a string is the key and the amount of times that word appears is the value.

var txtArray = txtVar.split(" "); var txtMap = {}; for (var i = 0; i<txtArray.length;i++){ if(txtArray[i] in txtMap) txtMap[txtArray[i]] += 1; else txtMap[txtArray[i]] = 1; } 

Now i need to sort them so that I can somehow rank them by the 10 longest words and 10 most used words and so on and I guess I could find a way to do it by making a for loop where i stored them in arrays and then pushed the oldest "top" word up or down the list when a new one comes along, but I think there must be a less awkward way to do this task?

2
  • Object.keys(txtMap).sort((a, b) => txtMap[a] < txtMap[b] ? -1 : txtMap[a] > txtMap[b] ? +1 : 0). Commented Oct 11, 2016 at 4:43
  • Note that in also checks the prototype chain, so txtMap[txtArray[i]] += 1 may have unexpected results in apparently random and difficult to find cases. Commented Oct 11, 2016 at 4:44

2 Answers 2

2

It's probably an adequate approach to do as you're currently doing, then sorting/slicing those results when you're done:

var allWords = Object.keys(txtMap); var tenMostFrequent = allWords .sort((a, b) => txtMap[b] - txtMap[a]) .slice(0, 10); var longestWords = allWords .sort((a, b) => b.length - a.length) .slice(0, 10); 
Sign up to request clarification or add additional context in comments.

Comments

0

You can use Object.keys() to get an array of the words, then .sort() as you see fit and use .slice() to get the top 10:

var txtVar = "some sample input to have something to fill the array with - random words the in are the it the what with some random whatever what what ridiculous whatever hello goodbye words the to have"; var txtArray = txtVar.split(" "); var txtMap = {}; for (var i = 0; i<txtArray.length;i++){ if(txtArray[i] in txtMap) txtMap[txtArray[i]] += 1; else txtMap[txtArray[i]] = 1; } var tenLongest = Object.keys(txtMap).sort(function(a, b) { return b.length - a.length; }).slice(0, 10); console.log("Longest: ", tenLongest.join(", ")); var tenMostUsed = Object.keys(txtMap).sort(function(a, b) { return txtMap[b] - txtMap[a]; }).slice(0, 10) .map(function(v) { return v + " (" + txtMap[v] + ")"; }); console.log("Most used: ", tenMostUsed.join(", ") );

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.