Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting Occurrences of Object Values

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.

like image 460
Miura-shi Avatar asked Dec 20 '22 04:12

Miura-shi


1 Answers

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.

like image 121
S McCrohan Avatar answered Dec 24 '22 02:12

S McCrohan