Reputation: 99
I have an array of people. I want to get the counts of the entire list grouped by each Level and Gender combination. I want to store these results in separate variables that I can display whenever I want in any order.
For instance, get the count for Level B Males and store that in a variable, Level B Females and store that in a variable, and Level B Nonbinary, Level A Males, Level A Females, and Level A Nonbinary, and so on through other levels storing those in their own variables. If storing them in an array is better (and it probably is), the order stored should be Level A Male, Female, Binary down to level Z Male, Female, Binary.
Also, I would like the totals of each Level as well.
I wrote up some stuff in the jsfiddle using a filter, but I've only done Level A. It will be too many lines of code doing Level B, C, D, etc. I think it can be much shorter and cleaner using a loop or something. Can anyone help me find a more efficient method? http://jsfiddle.net/cM94j/2/
var list ={"PEOPLE": [
{ "name": "Bob", "level": "A", "gender": "F"},
{ "name": "Sue", "level": "B", "gender": "F"},
{ "name": "Molly", "level": "A", "gender": "M"},
{ "name": "Joe", "level": "B", "gender": "N"},
{ "name": "Jack", "level": "B", "gender": "F"}
]};
Also, at most this list will have ~80 people and Levels A-H. Going off tangent, with those specs, would I be better off putting this data into a spreadsheet of some kind like excel. It's not a big enough project for a database. How would I output to a website if I do go that route? Should I be outputting these server-side instead of using jQuery?
Upvotes: 0
Views: 1261
Reputation: 63327
Here is the pure JS implementation you may want to use:
var list ={"PEOPLE": [
{ "name": "Bob", "level": "A", "gender": "F"},
{ "name": "Sue", "level": "B", "gender": "F"},
{ "name": "Molly", "level": "A", "gender": "M"},
{ "name": "Joe", "level": "B", "gender": "N"},
{ "name": "Jack", "level": "B", "gender": "F"}
]};
var counts = {};
var gender = {
F : "Female",
M : "Male",
N : "Neutral"
};
for(var i = 0; i < list.PEOPLE.length; i++){
var key = list.PEOPLE[i].level + "_" + list.PEOPLE[i].gender;
if(!counts[key]) counts[key] = 0;
counts[key]++;
}
//try printing out the result
for(var prop in counts){
var subKey = prop.split('_');
var level = subKey[0];
var gen = subKey[1];
$('#dir2').append("Level " + level + " " + gender[gen] +
": " + counts[prop] + "<br/>");
}
If you want to get the count of a combination (between level and gender), just build the key
by the format: level_gender
(the abbreviation of gender) and pass in the counts
to get the count.
Upvotes: 2
Reputation: 17481
Grouping can be done easily with underscore's groupBy method
var grp=_.groupBy(list.PEOPLE, function(person){ return person.level+'_'+person.gender });
grp would be
Object {A_F: Array[1], B_F: Array[2], A_M: Array[1], B_N: Array[1]}
unfortunately, you have no way to control the key order in a JS object.
Upvotes: 0