0

I have node 'messages' , and it will have multiple records with timestamp. I need to group by records by date,month, year as like below

12 July, 2016
13 July, 2016
14 July, 2016
.....

My records look like

{
  "messages" : {
    "233110" : {
      "-KMU3Tfp7Sk8DzT0Z_lu" : {
        ".priority" : 1468326341669,
        "message" : "hi",
        "timestamp" : 1468326341669
      },
      "-KMU3_u-x4RAWXw78MHe" : {
        ".priority" : 1468326371206,
        "message" : "yes",
        "timestamp" : 1468326371206
      },
}      

I would like to display these message

12 July, 2016
    Hi
    Yes
    ....

13 July, 2016
    Hi
    Yes
    ....

My code :

var temp_array = new Array();
var m_array = new Array();
chat.messageRef.child(roomId).on('child_added', function(snapshot,prevChildKey) { 
    var msg    = snapshot.val();
    var d      = new Date(msg.timestamp);
    var month  = d.getDate() +' '+chat.monthNames[d.getMonth()] + ", " + d.getFullYear();
    m_array.push(msg);
    temp_array[month] = m_array;
});    
console.log(temp_array); 
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Alice
  • 25
  • 2
  • 9

1 Answers1

0

There are a few problems in your question. I will focus on grouping the items by date.

ref.on('child_added', function(snapshot) {
  var msg    = snapshot.val();
  var date = new Date(msg.timestamp);
  var id = 'date_'+ date.toISOString().substring(0,10); // e.g. 'day_2016-07-13'
  // get or create the li for this date from the DOM
  var li = document.getElementById(id);
  if (!li) {
    li = document.createElement('li');
    li.id = id;
    li.innerHTML = '<b>' + date.toDateString() + '</b><br>';
    ul.appendChild(li);
  }
  li.innerHTML = li.innerHTML + msg.message + '<br>';
});

For each child we receive, we grab the date from the snapshot and convert it into a so-called ISO String. The first 10 characters of that are the date, e.g. '2016-07-13'. This is a great unique identifier for the date, so we use that to find/create an li element in the HTML.

Once we've found-or-created our li element, we can safely add our message to it. The last line does that.

Working sample in a jsbin: http://jsbin.com/lexaciy/edit?html,js,output

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807