Skip to content

Instantly share code, notes, and snippets.

@markthethomas
Created September 24, 2015 15:56
Show Gist options
  • Save markthethomas/ca62566f7e00602fd5af to your computer and use it in GitHub Desktop.
Save markthethomas/ca62566f7e00602fd5af to your computer and use it in GitHub Desktop.
Counting Arrays one-liner(s)
function count(array) {
return array.reduce((accumulator, current) => {
accumulator[current] = ++accumulator[current] || 1;
return accumulator;
}, {});
}
// Explanation: takes in an array and iterates over it with the reduce function. A callback is fired on each
// item in the array, with an accumulator and current value as args. The key thing is seeing that the default value of
// the accumulator is set to an object that we can write to ({}). Then, as we iterate through the values,
// the function will perform an assignment. It looks up the current object value and does a prefix incremented assignment.
// If that returns false (because there's no previous value), it sets the value to 1.
// Alternative approach:
// return the accumulator and use a ternary expression to do the same sort of thing and then return the accumulator
function count(array){
return array.reduce((accumulator, current) => {
return accumulator[current] ? accumulator[current]++ : accumulator[current] = 1, accumulator;
}, {});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment