Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning objects into an array of counts

I'm trying to wrap my mind around a problem I need solved, but I don't seem to get anywhere. What I want done is most likely easier to exemplify.

I have an array of objects, looking like this:

[
  {"city_name": "New York", "visited": "2014-10-20"},
  {"city_name": "New York", "visited": "2014-10-20"},
  {"city_name": "New York", "visited": "2014-10-20"},
  {"city_name": "New York", "visited": "2014-10-21"},
  {"city_name": "New York", "visited": "2014-10-21"},
  {"city_name": "Stockholm", "visited": "2014-10-20"},
  {"city_name": "Stockholm", "visited": "2014-10-20"},
  {"city_name": "Stockholm", "visited": "2014-10-21"},
  {"city_name": "Stockholm", "visited": "2014-10-21"},
]

Now, what I want to achieve is to turn this array into the following:

[
  {
    "key": "New York",
    "values": [
       ['2014-10-20', 3], // Because there were 3 visits in New York at this date
       ['2014-10-21', 2]  // Because there were 2 visits in New York at this date
    ]
  },
  {
    "key": "Stockholm",
    "values": [
       ['2014-10-20', 2],
       ['2014-10-21', 2]
    ]
  }
]

I tried using a MapReduce function (from Underscore.js) to solve this, but after failing to generate the output I wanted, and with the same (failed) result from a few other for-tries, I decided to ask here. Maybe someone knows what must be done?

And, sorry for the horrible title. If you've got a better idea for it, please comment (might help others reach this question as well)

like image 880
AndreasB Avatar asked Dec 25 '22 02:12

AndreasB


1 Answers

You can create an intermediate data structure to keep track of both countries and visits to each country; then you map that structure into the final output:

var tmp = {};

visits.forEach(function(item) {
  var obj = tmp[item.city_name] || (tmp[item.city_name] = {});

  obj[item.visited] = (obj[item.visited] || 0) + 1;
});

var result = Object.keys(tmp).map(function(key) {
  return {
    key: key,
    values: Object.keys(tmp[key]).map(function(date) {
      return [date, tmp[key][date]];
    })
  };
});
like image 113
Ja͢ck Avatar answered Jan 03 '23 08:01

Ja͢ck