Skip to content

Instantly share code, notes, and snippets.

@lewisrodgers
Last active January 27, 2017 13:54
Show Gist options
  • Save lewisrodgers/ffd52527dd9af68144d314085a2db6c5 to your computer and use it in GitHub Desktop.
Save lewisrodgers/ffd52527dd9af68144d314085a2db6c5 to your computer and use it in GitHub Desktop.
Reducer: Count number of unique items in a list
var list = ["foo", "foo", "bar", "bar", "bar"];
var results = list.reduce(reducer, {});
console.log(results); // {"foo": 2, "bar": 3}
/**
* Callback function for the `reduce()` method.
*
* @param acc accumulated value previously returned in the last invocation of the callback
* @param curr current element being processed in the array
*/
function reducer(acc, curr) {
if (!acc[curr]) {
acc[curr] = 1;
} else {
acc[curr] = acc[curr] + 1;
}
return acc;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment