JavaScript: get unique values โ€‹โ€‹and their number from an array of objects?

Using jQuery, how can I iterate over an object and get unique key values โ€‹โ€‹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 would like to get the following:

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

I have this one that works, but a little awkward:

 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; } } 
+6
source share
1 answer

you can use map for this purpose like:

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

I can also tell you that although this code is good to look and compact, it is not so fast. Better make your code faster and easier to use:

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

Source: https://habr.com/ru/post/924851/


All Articles