按事件排序对象

时间:2016-02-08 07:38:10

标签: javascript html

我有以下代码创建每个单词的对象( wordsArray 中的单词)并检查每个单词的出现次数,并将其与每个对象一起存储。

var wordOccurrences = { };
for (var i = 0, j = wordsArray.length; i < j; i++) {
        wordOccurrences[wordsArray[i]] = (wordOccurrences[wordsArray[i]] || 0) + 1;
}
console.log(wordOccurrences);

输出:

Object { hello: 1, world!: 2, click: 1, here: 1, goodbye: 1 }

如果有人能帮我订购物品,我会很感激,例如:升序或降序。我尝试了几种方法,但没有一种方法产生正确的结果。

所需的输出类似于:

world! 2 
hello 1 
click 1 
here 1 
goodbye 1

2 个答案:

答案 0 :(得分:1)

尝试以下方法:

var wordOccurences = { "hello": 1, "world!": 2, "click": 1, "here": 1, "goodbye": 1 }
var sortable = [];
for (var word in wordOccurences)
      sortable.push([word, wordOccurences[word]])
sortable.sort(function(a, b) {return a[1] - b[1]}).reverse()
var result = {}
for(var i = 0; i < sortable.length; i++){
result[sortable[i][0]] = sortable[i][1]
}

的console.log(结果);

答案 1 :(得分:1)

只需为密钥取一个数组并对其进行排序。

var wordOccurrences = { hello: 1, 'world!': 2, click: 1, here: 1, goodbye: 1 },
    words = Object.keys(wordOccurrences).sort(function (a, b) {
        return wordOccurrences[b] - wordOccurrences[a] || a.localeCompare(b);
    });

document.write(words.map(function (a) {
    return a + ': ' + wordOccurrences[a];
}).join('<br>'));