Skip to content

Instantly share code, notes, and snippets.

@mitchallen
Created December 24, 2018 16:01
Show Gist options
  • Save mitchallen/18d1fd08f82cd2936abdbf990d3b9723 to your computer and use it in GitHub Desktop.
Save mitchallen/18d1fd08f82cd2936abdbf990d3b9723 to your computer and use it in GitHub Desktop.
Use reduce to count the occurrence of an item in a list.
/*
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