How to add a block if it does not exist?

Good day!
There is a json in this format
{
 "dialog": [
{
 "date": "16-04-2020",
 "time": "10:35",
 "text": "message Text 3"
},
{
 "date": "16-04-2020",
 "time": "09:16",
 "text": "message Text 2"
},
{
 "date": "15-04-2020",
 "time": "18:59",
 "text": "Text message 1"
}
]
}

$.ajax({
 url: 'chat.php',
 type: "GET",
 dataType: "json",
 success: function(json) {
 if (typeof(json.dialog) == 'object') {
 $('div.dialog').append(json.dialog.map(function(n) {
 return '<div><span name="text">' + n.text + '</span><span name="time">' + n.time + '</span></div>';
}).join("));
}
}
});

How to display blocks in this format:
<div class="dialog">
the <div>16-04-2020</div>
 the <div><span name="text">message Text 3</span><span name="time">10:35</span></div>
 the <div><span name="text">message Text 2</span><span name="time">09:16</span></div>
the <div>15-04-2020</div>
 the <div><span name="text">message Text 1</span><span name="time">18:59</span></div>
</div>

ie need to display the block with the date
the <div>%date%</div>
And then display all records related to this date, and so on.
April 19th 20 at 12:21
2 answers
April 19th 20 at 12:23
Solution
if (typeof(json.dialog) == 'object') {

 const _dialog = json.dialog.reduce((acc,cur,i,a)=>{
 const index = acc.findIndex(item => item.date === cur.date) 
 if( index !== -1 ){
 acc[index].message.push({text: cur.text, time: cur.time})
}else{
 cur.message = []
 cur.message.push({text: cur.text, time: cur.time})
acc.push(cur)
}

 return acc
},[])

 $('div.dialog').html(_dialog.map(item => {
 let div = `<div>${item.date}</div>`
 item.message.forEach(_item => {
 div += `<div><span name="text">${_item.text}</span><span name="time">${_item.time}</span></div>`
})
 return div;
}).join("));

}
I hope you put this code in f-tion

success: function(json) {
...
} - helen commented on April 19th 20 at 12:26
April 19th 20 at 12:25
1. Upon shipment of json is to pass it to another function.
2. Which will receive the data and process to, ideally, sort by date.
3. Even easier is to create an array of objects, where will be:
[
{
 date:.
 messages: [...]
},
]

Such an object is simply stupid easier to bring into the template.
4. Then bring all this shit on the conditions: date + messages that this date coincides.

Find more questions by tags jQueryJavaScriptAJAX