'JS group by month of date values (objects) in an array

My array is like this:

myArray = [
  {date: "2017-01-01", num: "2"}
  {date: "2017-01-02", num: "3"}
  {date: "2017-02-04", num: "6"}
  {date: "2017-02-05", num: "15"}
]

I want to convert this into:

myArray = [
   {group: "0", data: [
      {date: "2017-01-01", num: "2"}
      {date: "2017-01-02", num: "3"}]
   },
   {group: "1", data: [  
      {date: "2017-02-04", num: "6"}
      {date: "2017-02-05", num: "15"}]
   },
]

Basically, group by month of date key.



Solution 1:[1]

The solution using Array.prototype.reduce, String.prototype.split and Array.prototype.map functions:

var myArray = [
    {date: "2017-01-01", num: "2"},
    {date: "2017-01-02", num: "3"},
    {date: "2017-02-04", num: "6"},
    {date: "2017-02-05", num: "15"}
],
    groupKey = 0;
    groups = myArray.reduce(function (r, o) {
        var m = o.date.split(('-'))[1];
        (r[m])? r[m].data.push(o) : r[m] = {group: String(groupKey++), data: [o]};
        return r;
    }, {});

var result = Object.keys(groups).map(function(k){ return groups[k]; });

console.log(result);

Solution 2:[2]

Pro Solution (One Liner):

If you don't already have Lodash (same as Underscore JS), add it to your JS, like this:

Install with NPM: npm i --save lodash

The Solution Code:

I will show you a beautiful one liner in Lodash (or Underscore.js)

const _ = require('lodash');
let myArray = [
  {date: "2017-01-01", num: "2"},
  {date: "2017-01-02", num: "3"},
  {date: "2017-02-04", num: "6"},
  {date: "2017-02-05", num: "15"}
]

// The one liner
_.groupBy(myArray, ({date})=> new Date(date).getMonth());

This is the response:

{
    "0": [
           {
            "date": "2017-01-01",
            "num": "2"
           },
           {
            "date": "2017-01-02",
            "num": "3"
           }
    ],
    "1": [
           {
            "date": "2017-02-04",
            "num": "6"
           },
           {
            "date": "2017-02-05",
            "num": "15"
           }
    ]
}

Group By Reference

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2