簡體   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