JS group by month of date values (objects) in an array
Asked Answered
S

2

9

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.

Stockdale answered 27/1, 2017 at 7:26 Comment(1)
Please share your codeTortosa
I
10

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);
Indefinable answered 27/1, 2017 at 7:43 Comment(1)
How to do exact same thing but sum all values (nums) by group without putting them to data array? Just wanna group and sum value.Cowgill
S
7

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

Swiercz answered 18/1, 2022 at 9:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.