Created
February 27, 2015 23:04
-
-
Save prestonp/851a76def41181b7ba2a to your computer and use it in GitHub Desktop.
Count By
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// count # of any object property | |
var getProperty = function( obj, prop ) { | |
if (prop.indexOf('.') < 0) return obj[prop]; | |
var parts = prop.split('.') | |
, last = parts.pop() | |
, len = parts.length | |
, idx = 1 | |
, current = parts[0]; | |
while( (obj = obj[current]) && idx < len ) { | |
current = parts[idx++]; | |
} | |
if ( obj ) | |
return obj[last]; | |
return obj; | |
} | |
var countBy = function(list, prop) { | |
return list.reduce(function(histogram, obj) { | |
var key = getProperty(obj, prop); | |
if ( key ) histogram[key] = histogram[key] ? histogram[key]+1 : 1; | |
return histogram; | |
}, {}); | |
} | |
// Example | |
var orders = [ | |
{ id: 1, user: { name: 'Sam' } } | |
, { id: 2, user: { name: 'Dan' } } | |
, { id: 3, user: { name: 'John' } } | |
, { id: 4, user: { name: 'Gillian' } } | |
, { id: 5, user: { name: 'John' } } | |
, { id: 6, user: { name: 'Sam' } } | |
]; | |
countBy(orders, 'user.name'); | |
// { Sam: 2, Dan: 1, John: 2, Gillian: 1 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment