How to use moment and lodash to group by fields of objects and count by dates?

I have a pretty difficult situation and I'm not sure how to convert it using lodash and the moment. Let's say that I have a date range and this source data.

var startDate = "2018-02-21"
var endDate = "2018-02-23"
var data = [
      {
       "date": "2018-02-21 21:21:17",
       "group": "A"
       },
      {
       "date": "2018-02-21 21:21:17",
       "group": "B"
       },
      {
       "date": "2018-02-23 21:21:17",
       "group": "A"
       },
      {
       "date": "2018-02-21 21:21:17",
       "group": "B"
       }
  ];

I would like to use lodash to group all the "group" fields and a new field in a new object named "date", which will be a key / date value pair. The keys will be a date range (from startDate to endDate), and the values ​​will be the number of matching dates.

The new output will look like this:

 var output = [
    {
        "group": "A",
        "dates": [
            "2018-02-21": 1,
            "2018-02-22": 0
            "2018-02-23": 1
        ]
    },
    {
        "group": "B",
        "dates": [
            "2018-02-21": 2,
            "2018-02-22": 0,
            "2018-02-23": 0
        ]
    }
  ];

I created jsfiddle and imported the moment and lodash of this situation.

http://jsfiddle.net/dp7rzmw5/6467/

Thank you so much if you can help!

+4
source share
1

javascript.

dates . , data .

var dates = [];
var startDate = new Date("2018-02-21");
var endDate = new Date("2018-02-23");
for (var s = startDate; s <= endDate; s.setDate(s.getDate() + 1)) {
    dates.push(s.toISOString().split('T')[0]);
}

dates - : [ "2018-02-21", "2018-02-22", "2018-02-23" ].

.reduce() data , .forEach() dates, , .

var groups = [];
var output = data.reduce((obj, item) => {
    var d = new Date(item.date).toISOString().split('T')[0];
    var x = groups.indexOf(item.group);
    if (x === -1) {
        groups.push(item.group);
        x = groups.indexOf(item.group);
    }
    obj[x] = obj[x] || {};
    obj[x]["date"] = obj[x]["date"] || {};
    dates.forEach(date => {
        if (!obj[x]["date"][date]) {
            obj[x]["date"][date] = 0;
        }
    });
    obj[x]["date"][d]++;
    obj[x]["group"] = item.group;
    return obj;
}, {});

:

{
  "0": {
    "date": {
      "2018-02-21": 1,
      "2018-02-22": 0,
      "2018-02-23": 1
    },
    "group": "A"
  },
  "1": {
    "date": {
      "2018-02-21": 2,
      "2018-02-22": 0,
      "2018-02-23": 0
    },
    "group": "B"
  }
}

- console.table(output).

jsfiddle.

+2

Source: https://habr.com/ru/post/1694003/


All Articles