我使用数组来存储文本中特定单词的出现次数。数据格式为word:number。 我想通过降低出现次数(即按值)对数组进行排序。 有一个简洁的方法吗?或者我应该考虑使用不同的数据结构?
// This is how the array is filled.
var matches = ["word1", "word2", "word2", "word3", "word4", "word4", "word4"];
var count = {};
$.each(matches, function(key, value) {
if(!count[value])
count[value] = 1;
else
count[value]++;
});
循环之后,这就是我得到的,并希望按降序值排序:
count = { 'word1':'1', 'word2':'2', 'word3':'1', 'word4':'3' };
我真正希望它看起来像(按值排序):
count = { 'word4':'3', 'word2':'2', 'word1':'1', 'word3':'1' };
答案 0 :(得分:8)
试试这个:
function sortmyway(data_A, data_B)
{
return (data_A - data_B);
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[9, 18, 21, 39, 55, 108]
答案 1 :(得分:-1)
我建议您使用某种树,因为它已经具有已排序地图的属性。