Last active
January 27, 2017 13:54
-
-
Save lewisrodgers/ffd52527dd9af68144d314085a2db6c5 to your computer and use it in GitHub Desktop.
Reducer: Count number of unique items in a list
This file contains hidden or 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
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