简体   繁体   中英

JavaScript: Get unique values and their counts from an array of objects?

Using jQuery, how can I iterate over an object, and get the unique values of a key with a count of each value?

For example, for this array:

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 }, 
];

I'd like to get back the following:

var distance_counts = {1: 2, 2: 8, 3: 1};

I've got this, which works but is a bit clumsy:

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;
    } 
}

you could use map for this purpose as:

var distances = {};
$.map(electrons,function(e,i) {
   distances[e.distance] = (distances[e.distance] || 0) + 1;
});

or

var distances = {};
$.each(electrons,function(i,e) {
   distances[this.distance] = (distances[this.distance] || 0) + 1;
});

Also may I point out to you that although this code good to look and compact, this is not generally faster. Better make your code more faster and more easy to look at as:

var distances = {},e;
for (var i = 0,l=electrons.length; i < l; i++) { 
    e = electrons[i];
    distances[e.distance] = (distances[e.distance] || 0) + 1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM