Underscore Find Object in Collection V2
by mrrodd
JavaScript
var states = [
{"Name": "AZ"},
{"Name": "CA"},
{"Name": "TN"},
{"Name": "AZ"},
{"Name": "TX"},
{"Name": "TN"}
];
var stateSummary = [];
// Loop through the various states
_.each(states, function(state) {
// Check if the state is already in the stateSummary array.
var stateFound = _.find(stateSummary, function(item) {
return item.Name == state.Name;
});
// Add the state to the stateSummary array, if it does not
// exist. Otherwise increment the state count.
if( stateFound == undefined) {
stateSummary.push({"Name": state.Name, "Count": 1});
} else {
stateFound.Count = parseInt(stateFound.Count) + 1;
}
});
console.log(stateSummary);