简体   繁体   English

JavaScript:从一组对象中获取唯一值及其计数?

[英]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? 使用jQuery,我如何迭代一个对象,并获得具有每个值的计数的键的唯一值?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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