Milind Rasal
Milind Rasal

Reputation: 19

Javascript group the json object by month

I have a json object which has a date entries. In the below json object there is date entries under "timestamp" key. I am trying to add those date entries under respective month. For exp. if there is dates from March month then I want add these all entries under March month.

[{
  "request":"S034749",
  "response":"Cardcode : null Is On Hold :null Is on terms : null CreditAvailable : null",
  "status":"Success",
  "refID":"6884d5d7-124b-4ab6-83b4-a61c95a16512",
  "errorMessage":null,
  "timestamp":"2014-03-13"
 },
 {
  "request":"S034749",
  "response":"Cardcode : null Is On Hold :null Is on terms : null CreditAvailable : null",
  "status":"failure",
  "refID":"e6c3fc16-15d3-461d-bab2-c3a6ea457a4a",
  "errorMessage":null,
  "timestamp":"2014-03-13"
 },
 {
  "request":"S034749",
  "response":"Cardcode : null Is On Hold :null Is on terms : null CreditAvailable : null",
  "status":"Success",
  "refID":"1c0c6735-f8ed-415a-a39b-1aca466ffdf0",
  "errorMessage":null,
  "timestamp":"2014-03-13"
 },
 {
  "request":"S034749",
  "response":"Cardcode : null Is On Hold :null Is on terms : null CreditAvailable : null",
  "status":"failure",
  "refID":"71a7d08a-a978-4b98-bb14-5f907f0f9135",
  "errorMessage":null,
  "timestamp":"2014-03-13"
}],

Upvotes: 0

Views: 2696

Answers (2)

NimChimpsky
NimChimpsky

Reputation: 47290

myArray.sort(function(a, b) {
    return new Date(b.timestamp) - new Date(a.timestamp);
});

And to get each march, using array filter :

var marchArray = myArray.filter(function(o){
  var myDate = new Date(o.timestamp);
  return myDate.getMonth() === 2; // getDate is zero based
})

Upvotes: 0

Iftah
Iftah

Reputation: 9572

Iterate over the objects, get the month, append to list of that month.

Note: grouped by month - June 2014 will be in the same group as June 2013.

function group_by_month(data) {
    var months = {}
    for (var i=0; i<data.length; i++) {
       var obj = data[i];
       var date = new Date(obj.timestamp);
       var month = date.getMonth();
       if (months[month]) {
           months[month].push(obj);  // already have a list- append to it
       }
       else {
           months[month] = [obj]; // no list for this month yet - create a new one
       }
    }
    return months;
 }


 result = group_by_month(data);
 console.log("Items of January are ", result[0])
 console.log("Items of February are ", result[1])

Upvotes: 3

Related Questions