Created
December 24, 2018 16:01
-
-
Save mitchallen/18d1fd08f82cd2936abdbf990d3b9723 to your computer and use it in GitHub Desktop.
Use reduce to count the occurrence of an item in a list.
This file contains 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
/* | |
Using reduce to count the occurrence of an item in a list. | |
[ 'd', 'a', 'b', 'a', 'b', 'c', 'd', 'b', 'd', 'd' ] | |
a occurs 2 times in the list. | |
b occurs 3 times in the list. | |
c occurs 1 time in the list. | |
d occurs 4 times in the list. | |
*/ | |
const list = [ 'd', 'a', 'b', 'a', 'b', 'c', 'd', 'b', 'd', 'd'] | |
function countTimes( item ) { | |
const count = list.reduce( (prev, curr) => prev += curr == item ? 1 : 0, 0); | |
console.log( `${item} occurs ${count} time${ count == 1 ? '' : 's'} in the list.` ); | |
} | |
console.log(list); | |
countTimes('a'); | |
countTimes('b'); | |
countTimes('c'); | |
countTimes('d'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment