0

I'm fetching data using ajax. It works, and I get each piece of data as intended. But I would like to group data for each day. How can I do that?

What I have:

Sat Mar 03 2018 12:48:15 GMT+0100: Message 1
Sat Mar 03 2018 12:14:38 GMT+0100: Message 2
Fri Mar 02 2018 19:41:54 GMT+0100: Message 3
Fri Mar 02 2018 19:25:16 GMT+0100: Message 4
Fri Mar 02 2018 14:02:45 GMT+0100: Message 5
Wed Feb 28 2018 18:01:13 GMT+0100: Message 6

What I would like:

Sat Mar 03 2018: Message 1, Message 2
Fri Mar 02 2018: Message 3, Message 4, Message 5
Wed Feb 28 2018: Message 6

My (simplified) ajax:

$.ajax({
  type: 'GET',
  url: "my-url",
  dataType: "json",
  success: function(data) {
    $.each(data, function(k, v) {
      var date = v.date;
      var message = v.message;
      var t = new Date(date);
      $('body').append(t + ': ' + message);
    });
  }
});

Can anyone point me in the right direction, please? Thanks.

Meek
  • 3,086
  • 9
  • 38
  • 64
  • Why the "ajax" reference if this has nothing to do with the actual problem (grouping an array of objects)? – Andreas Mar 03 '18 at 15:26
  • Possible duplicate of [What is the most efficient method to groupby on a JavaScript array of objects?](https://stackoverflow.com/questions/14446511/what-is-the-most-efficient-method-to-groupby-on-a-javascript-array-of-objects) – Andreas Mar 03 '18 at 15:27

1 Answers1

0

You can reduce the array you are getting to a different representation like

{
  "date": ["Message 1", "Message 2"],
  ... 
}

// This will format the data
var newData = data.reduce(
  (acc, el) => {
    var date = el.date;
    if (acc.hasOwnProperty(date))
      acc[date].push(el.message);
    else
      acc[date] = [el.message];
    return acc;
  }, {}
)

// Now iterate over the keys and build the HTML
Object.keys(newData).forEach(function(v, k) {
  var date = v;
  var message = newData[v].join(", ");
  var t = new Date(date);
  $('body').append(t + ': ' + message);
});
void
  • 36,090
  • 8
  • 62
  • 107