简体   繁体   中英

How Can I Sort an Object so that all the values are in ascending order?

I am trying to do word frequency and I have something working as far as printing out the word frequency. I now want to sort the output in Ascending Order.

var paragraph = "Into the bored patent composes the synonymous cheer. The playing essence mothers an offset. Does the alleged cap fast? Why can't the covered fish urge the word? The cyclist works within a laughing jam. When will my smooth year entitle the public?";

un_puncutated_paragraph = paragraph.replace(/[~`!@#$%^&*(){}\[\];:"'<,.>?\/\\|_+=-]/g,"");
let wordsHolder = un_puncutated_paragraph.split(' ');
let frequencyMap = {};

wordsHolder.forEach((word) => {
  if (!frequencyMap[word]) {
    frequencyMap[word] = 0;
  }
  frequencyMap[word] += 1;
});

Also, could someone explain this logic a bit better, not entirely sure what is going on?

  if (!frequencyMap[word]) {
    frequencyMap[word] = 0;
  }
  frequencyMap[word] += 1;

Thanks!

 var paragraph, arrText, getVal, finalString; var objText = [], arrGetText = []; paragraph = "Into the bored patent composes the synonymous cheer. The playing essence mothers an offset. Does the alleged cap fast? Why can't the covered fish urge the word? The cyclist works within a laughing jam. When will my smooth year entitle the public?"; // Step 1. Split Text with space arrText = paragraph.split(" "); // Step 2. Create length and text based object for (var index = 0; index < arrText.length; index++) { objText.push({ len: arrText[index].length, text: arrText[index] }); } // Step 3. Sort object by length objText.sort(function(a, b) { return a.len - b.len; }); // Step 4. Extract value from sorted object and push into a new array for (var index = 0; index < arrText.length; index++) { getVal = Object.values(objText[index]); arrGetText.push(getVal[1]); } // Step 5. Finally join array with with space and produce ascending order sorted string. var finalString = arrGetText.join(" "); console.log(finalString); 

 if (!frequencyMap[word]) { // If word does not exists as key in array...
    frequencyMap[word] = 0; // ...add key in array
  }
 frequencyMap[word] += 1; //  if existing or just created increment word count

To sort your final frequencyMap object by the frequency of each word you can try:

Object.keys(frequencyMap)
    .sort()
    .reduce((a, v) => {
      a[v] = frequencyMap[v];
      return a; }, {});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM