繁体   English   中英

如何对对象进行排序,以使所有值都按升序排列?

[英]How Can I Sort an Object so that all the values are 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;
});

另外,有人可以更好地解释这种逻辑,而不是完全确定发生了什么吗?

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

谢谢!

 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

要按每个单词的频率对最终的frequencyMap对象进行排序,可以尝试:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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