Turning objects into an array of counters

I'm trying to think about a problem that I need to solve, but it seems like I'm not going anywhere. What I want to do is most likely easier to illustrate.

I have an array of objects that looks 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 I want this array to include 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 the MapReduce function (from Underscore.js) to solve this problem, but after I could not generate the desired result, and with the same (unsuccessful) result of several other attempts, I decided to ask here, Maybe someone Does anyone know what needs to be done?

And, sorry for the terrible title. If you have a better idea for this, please comment (may help others reach this point as well)

+4
source share
5

Underscore :

var result = _.chain(arr).groupBy('city_name').map(function (el, key) {
    return {
        key: key,
        values: _.chain(el).countBy('visited').pairs().value()
    }
}).value();
+3

; :

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]];
    })
  };
});
+4

here you go:

function make_it_so(src)
{
    var usd={}, rsl=[], idx=-1;

    src.forEach(function(val,key,arr)
    {
        var cty = val["city_name"];

        if (!usd[cty])
        {
            idx++;
            usd[cty] = {};
            rsl[idx] = {"key":cty, "values":[]};
        }

        if (!usd[cty][val["visited"]])
        {
            usd[cty][val["visited"]] = val["visited"];
            rsl[idx]["values"][rsl[idx]["values"].length] = val["visited"];
        }
    });

    return rsl;
}

var src = [
    {"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"}
];

console.log(make_it_so(src));
+2
source

My solution uses a “shrink” and a “map” to compute counters and transform data:

function countVisitDates(visits) {
  // Count the visits per city per date using "reduce".
  var counts = visits.reduce(function(memo, visit) {
    var cityName=visit.city_name, visitDate=visit.visited;
    if (!memo[cityName]) { memo[cityName] = {}; }
    memo[cityName][visitDate] |= 0;
    memo[cityName][visitDate] += 1;
    return memo;
  }, {});
  // Transform the count structure using "map".
  return Object.keys(counts).map(function(cityName) {
    return {
      key: city_name,
      values: Object.keys(counts[cityName]).map(function(date) {
        return [date, counts[cityName][date]];
      })
    };
  });
};

countVisitDates(data);
/* =>
[
  {
    "key": "New York",
    "values": [
      [ "2014-10-20", 3 ],
      [ "2014-10-21", 2 ]
    ]
  },
  {
    "key": "Stockholm",
    "values": [
      [ "2014-10-20", 2 ],
      [ "2014-10-21", 2 ]
    ]
  }
]
*/
+1
source

You can simply view the data:

var data = [
  {"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"},
];

var newdata = {};

data.forEach(function(entry) {
  var city = entry.city_name;
  var time = entry.visited;
  if(!newdata[city]) {
    newdata[city] = {};
  }
  if(!newdata[city][time]) {
    newdata[city][time]=0;
  }
  newdata[city][time]++;
});

This gives an equivalence structure, which can then be transformed as necessary using Object.keys():

{
  "New York": {
    "2014-10-20": 3,
    "2014-10-21": 2
  }
  ,
  ...
}
0
source

All Articles