我在這裏有一個對象數組。下劃線:查找數組中最頻繁出現的對象?
var list = [
{"id": 439, "name": "John"},
{"id": 439, "name": "John"},
{"id": 100, "name": "Kevin"},
{"id": 120, "name": "Max"},
{"id": 439, "name": "John"}
];
我需要從這個數組中提取最常出現的對象,並按照最常用的名稱排序它。
到目前爲止,我已經嘗試遵循它從這個話題所做的那樣:Underscore.js: Find the most frequently occurring value in an array?
// Build temp list
temp_list = _(
_.chain(
_(list).pluck('id')
)
.countBy()
.pairs()
.value()
)
.sortBy(1)
.reverse();
// Build final list with most frequently occurring first
_.map(temp_list, function(current) {
return _.findWhere(list, {
'id': parseInt(current[0])
});
});
莫非存在的方式通過排序直接初始列表,而無需創建一個臨時表來改善這個代碼?
數組中的所有對象都不相同。如果兩個對象的'id'和'name'屬性重合,您是否想要考慮兩個對象?只有'id'? – Oriol