0

I found a solution for my problem. I tried and testes it and its working fine for me.

var obj = [{
  "message": "fsbdfs",
  "id": "8290",
  "readBy": "2016-05-25 06:17:01",
  "userID": "339",
  "dateTime": "2016-05-25 06:16:32"
}, {
  "message": "Hi",
  "id": "8291",
  "readBy": "2016-05-25 6:33:52",
  "userID": "332",
  "dateTime": "2016-05-25 06:17:06"
}, {
  "message": "nbfsdbf",
  "id": "8292",
  "readBy": "",
  "userID": "339",
  "dateTime": "2016-05-25 07:03:44"
}, {
  "message": "jsdhfjsdhf",
  "id": "8293",
  "readBy": "",
  "userID": "339",
  "dateTime": "2016-05-25 07:06:55"
}, {
  "message": "fbsnf",
  "id": "8294",
  "readBy": "",
  "userID": "339",
  "dateTime": "2016-05-25 07:06:59"
}, {
  "message": "dfgjdf",
  "id": "8295",
  "readBy": "",
  "userID": "339",
  "dateTime": "2016-05-25 07:08:14"
}, {
  "message": "sim",
  "id": "8296",
  "readBy": "",
  "userID": "339",
  "dateTime": "2016-05-25 07:24:24"
}, {
  "message": "mgmdf,",
  "id": "8297",
  "readBy": "",
  "userID": "339",
  "dateTime": "2016-05-25 10:16:34"
}, {
  "message": "bvd",
  "id": "8317",
  "readBy": "",
  "userID": "339",
  "dateTime": "2016-05-31 06:25:40"
}, {
  "message": "fdfd",
  "id": "8318",
  "readBy": "",
  "userID": "339",
  "dateTime": "2016-05-31 06:25:43"
}];

obj.sort(function(a, b) {
  return a.dateTime.localeCompare(b.dateTime)
});

var map = {};
obj.forEach(function(val) {
  var date = val.dateTime.split(" ")[0];
  map[date] = map[date] || [];
  map[date].push(val)
});

console.log(map)

I am unable to understand this part map[date] = map[date] || [];. Can anybody explain it? I was unable to comment on original post how to show data date wise according to json response?

Ivar
  • 4,655
  • 12
  • 45
  • 50
  • 1
    `map[date]` is a [bracket property accessor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#bracket_notation) so in that line you add a property which name is a `date` variable value (e.g. "2016-05-25"). The `|| []` part ensures that the first time this property value is initialized with empty array. – yuvin Apr 13 '21 at 09:59
  • @yuvin Thank you! I got it now :) – Logo Designer Apr 13 '21 at 10:56

0 Answers0