Created
February 27, 2017 23:08
-
-
Save aledwassell/b0648a6d79709db7868aae05e1fe8571 to your computer and use it in GitHub Desktop.
using reduce to count up the number of item in an array
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
//items to count | |
const votes = [ | |
'cow', | |
'sheep', | |
'duck', | |
'cow', | |
'cow', | |
'duck', | |
'pig', | |
'pig', | |
'goat', | |
'sheep', | |
'pig', | |
'cow', | |
'goat' | |
]; | |
//seeting the initial value to an object, this is where the 'key: value' pairs returned from the object will go | |
const initialValue = {}; | |
//the function takes the tally and the animal and this lives inside the reduce funtion | |
const reducer = (tally, animal) => { | |
//if inside the initial value there is no '!tally[animal]' for the current animal | |
if (!tally[animal]) { | |
//make one | |
tally[animal] = 1; | |
} else { | |
//if there is 'tally[animal]' for the current animal, add one to it | |
tally[animal] = tally[animal] + 1; | |
} | |
//return the tally, thats the object i.e the initial value as it is now | |
return tally; | |
} | |
const result = votes.reduce(reducer, initialValue); | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment