Skip to content

Instantly share code, notes, and snippets.

@KimSarabia
Last active September 29, 2017 19:43
Show Gist options
  • Save KimSarabia/f9eadcbeb86cf62060e55aa1401f1149 to your computer and use it in GitHub Desktop.
Save KimSarabia/f9eadcbeb86cf62060e55aa1401f1149 to your computer and use it in GitHub Desktop.
Creating Tally
//From Reduce - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?v=a
//Counting instances of values in an object
//Initializing with an empty object
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
var countedNames = names.reduce(function (allNames, name) {
if (name in allNames) {
allNames[name]++;
}
else {
allNames[name] = 1;
}
return allNames;
}, {});
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment