Skip to content

Instantly share code, notes, and snippets.

@johanbrook
Created July 14, 2014 11:22
Show Gist options
  • Save johanbrook/1db266e9e33e068f9776 to your computer and use it in GitHub Desktop.
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.
/*
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