I am trying to loop through some data in a JSON file and count the number of same cities/occurrences...
var json = [
{ "city": "California" },
{ "city": "California" },
{ "city": "California" },
{ "city": "Texas" },
{ "city": "Florida" }
];
var obj = {};
for (var i = 0, j = json.length; i < j; i++) {
if (obj[json[i]]) {
obj[json[i]]++;
}
else {
obj[json[i]] = 1;
}
}
console.log(obj);
JSFiddle: http://jsfiddle.net/f2939ucw/
The problem is that the object returned is only returning back the number of objects within the array and not the same occurrences of cities.
An alternate way of phrasing this:
json.reduce(function(sums,entry){
sums[entry.city] = (sums[entry.city] || 0) + 1;
return sums;
},{});
Array.reduce()
calls a callback on each element of the array, passing the return of the previous call in as the first parameter in the next. (The {}
at the end is the initial value, passed into the first call)
So this is doing exactly what you did - creating an empty object, iterating through the array, and accumulating totals inside the object. It's just doing it tersely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With