使用jQuery,我如何遍歷一個對象,並獲得一個密鑰的唯一值與每個值的計數?JavaScript:從一組對象中獲取唯一值和它們的計數?
例如,對於此陣:
var electrons = [
{ name: 'Electron1', distance: 1 },
{ name: 'Electron2', distance: 1 },
{ name: 'Electron3', distance: 2 },
{ name: 'Electron4', distance: 2 },
{ name: 'Electron5', distance: 2 },
{ name: 'Electron6', distance: 2 },
{ name: 'Electron7', distance: 2 },
{ name: 'Electron8', distance: 2 },
{ name: 'Electron9', distance: 2 },
{ name: 'Electron10', distance: 2 },
{ name: 'Electron11', distance: 3 },
];
我希望得到以下:
var distance_counts = {1: 2, 2: 8, 3: 1};
我這有,這工作,但有點笨拙:
var radius_counts = {};
for (var i = 0; i < electrons.length; i++) {
if (electrons[i].distance in radius_counts) {
radius_counts[electrons[i].distance] += 1;
} else {
radius_counts[electrons[i].distance] = 1;
}
}
試試這個http://stackoverflow.com/questions/1960473/unique-values-in-an-array –
@Artem - 這是一個完全關於獲取一組唯一值的不同問題。 – Richard
初始數組是否總是按原樣排序? – sp00m