[英]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: 要按每个单词的频率对最终的frequencyMap
对象进行排序,可以尝试:
Object.keys(frequencyMap)
.sort()
.reduce((a, v) => {
a[v] = frequencyMap[v];
return a; }, {});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.