Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summarise data using .countBy

I'm trying to work out how I can summarise the following data using the _.countBy() method in UnderscoreJS. I have the following data:

var data =
[
    {"id":"338b79f07dfe8b3877b3aa41a5bb8a58","value":{"country":"United States"}},
    {"id":"338b79f07dfe8b3877b3aa41a5bb983e","value":{"country":"Norway"}},
    {"id":"338b79f07dfe8b3877b3aa41a5ddfefe","value":{"country":"Hungary"}},
    {"id":"338b79f07dfe8b3877b3aa41a5fe29d7","value":{"country":"United States"}},
    {"id":"b6ed02fb38d6506d7371c419751e8a14","value":{"country":"Germany"}},
    {"id":"b6ed02fb38d6506d7371c419753e20b6","value":{"country":"Hungary"}},
    {"id":"b6ed02fb38d6506d7371c419755f34ad","value":{"country":"United States"}},
    {"id":"b6ed02fb38d6506d7371c419755f3e17","value":{"country":"Germany"}},
    {"id":"338b79f07dfe8b3877b3aa41a506082f","value":{"country":"United Kingdom"}},
    {"id":"9366afb036bf8b63c9f45379bbe29509","value":{"country":"United Kingdom"}}
]

I would like to summarise it like this:

{ 
    United_States: 3,
    Norway: 1,
    Hungary: 2,
    Germany: 2,
    United_Kingdom: 2
}

How would I pass this into the _.countBy() method provided by Underscore.js ?

like image 446
user1513388 Avatar asked Oct 07 '12 20:10

user1513388


1 Answers

Try this:

var data =
[
    {"id":"338b79f07dfe8b3877b3aa41a5bb8a58","value":{"country":"United States"}},
    {"id":"338b79f07dfe8b3877b3aa41a5bb983e","value":{"country":"Norway"}},
    {"id":"338b79f07dfe8b3877b3aa41a5ddfefe","value":{"country":"Hungary"}},
    {"id":"338b79f07dfe8b3877b3aa41a5fe29d7","value":{"country":"United States"}},
    {"id":"b6ed02fb38d6506d7371c419751e8a14","value":{"country":"Germany"}},
    {"id":"b6ed02fb38d6506d7371c419753e20b6","value":{"country":"Hungary"}},
    {"id":"b6ed02fb38d6506d7371c419755f34ad","value":{"country":"United States"}},
    {"id":"b6ed02fb38d6506d7371c419755f3e17","value":{"country":"Germany"}},
    {"id":"338b79f07dfe8b3877b3aa41a506082f","value":{"country":"United Kingdom"}},
    {"id":"9366afb036bf8b63c9f45379bbe29509","value":{"country":"United Kingdom"}}
];

var countData = _.countBy(data, function(obj){
    return obj.value.country.replace(" ", "_");
}); 

console.log(countData);

JSFiddle: http://jsfiddle.net/hyDv7/1/

like image 110
Chandu Avatar answered Nov 02 '22 13:11

Chandu