Created
September 8, 2015 10:01
-
-
Save chrislaughlin/7e4d52cb719de63fb045 to your computer and use it in GitHub Desktop.
Turn an array into a tally
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
var array = [ | |
{ | |
name: 'red', | |
vlaue: 7 | |
}, | |
{ | |
name: 'red', | |
vlaue: 7 | |
}, | |
{ | |
name: 'black', | |
vlaue: 7 | |
}, | |
{ | |
name: 'blue', | |
vlaue: 7 | |
}, | |
{ | |
name: 'black', | |
vlaue: 7 | |
}, | |
{ | |
name: 'green', | |
vlaue: 7 | |
}, | |
{ | |
name: 'red', | |
vlaue: 7 | |
} | |
]; | |
var arrayMap = {}; | |
array.forEach(function(item) { | |
arrayMap[item.name] = !_.isUndefined(arrayMap[item.name]) ? arrayMap[item.name] += 1 : 1; | |
}); | |
console.log(JSON.stringify(arrayMap)); | |
//{"red":3,"black":2,"blue":1,"green":1} | |
var tally = Object.keys(arrayMap).map(function(key) { | |
return [key, arrayMap[key]]; | |
}); | |
console.log(JSON.stringify(tally)); | |
//[["red",3],["black",2],["blue",1],["green",1]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment