Created
July 14, 2014 11:22
-
-
Save johanbrook/1db266e9e33e068f9776 to your computer and use it in GitHub Desktop.
Underscore mixin for finding number of occurrences of elements in an array. Optionally select an element to count.
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
/* | |
Usage: | |
_.occurrences(['Foo', 'Bar', 'Foo']) | |
=> {'Foo': 2, 'Bar': 1} | |
_.occurrences(['Foo', 'Bar', 'Foo'], 'Foo') | |
=> {'Foo': 2} | |
*/ | |
_.mixin({ | |
occurrences: function(array, needle) { | |
return _.reduce(array, function(counter, val) { | |
var key = needle || val; | |
counter[key] = counter.hasOwnProperty(key) ? counter[key] + 1 : 1; | |
return counter; | |
}, {}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment