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

时间:2022-09-25 10:23:53

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

1 个解决方案

#1


7  

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

#1


7  

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