I have an array object which gets populated from database.
dataObj = [
{
"id": "1",
"date": "Tue Nov 07 2023",
"month": "11",
"day": "Tuesday",
},
{
"id": "2",
"date": "Tue Nov 07 2023",
"month": "11",
"day": "Tuesday",
},
{
"id": "kGSykTUAd6gcEUmskMu6",
"date": "Wed Nov 08 2023",
"month": "11",
"day": "Wednesday",
},
]
Now I want the UI to be like this-
The common date is shown as one date on the left and other information on the right.
For example,
First two entries fall on the same date,
so the left should show one date i.e. Nov 7 and the right section should show all id, month, day for Nov 7.
But when I’m comparing the array and converting the duplicate dates as one and then displaying the date, it does not show the right output. The output is –
Nov 7 – id, date, month
Nov 7 – id, date, month
Correct Output should be
Nov 7
id, date, month
id, date, month
Nov 8
id, date, month
JS
let datesArr = []
// Pushing the data in the array.
datesArr.push( doc.data().dates )
// Removing same dates from the datesArr
let duplicates = datesArr.filter( function ( item, index, inputArray )
{
return inputArray.indexOf( item ) === index
} )
duplicates.sort( ( a, b ) =>
{
return a - b
} )
for ( let dupes of duplicates )
{
let myArr = []
let dupesDate = new Date( dupes ).toDateString()
for ( let content of dataObj)
{
if ( dupesDate === new Date( content.date).toDateString() )
{
myArr.push( content );
}
}
}
How do I fix this, I been struggling with this for few days now.
4
Answers
You can try using
Array.prototype.reduce()
:You can use below code snippet to convert it into your expected output,
You can try the below code:
Instead of creating intermediate variables (constants) and DOM objects and
append
ing them together you could also do it with a single.innerHTML
assignment. The simplified algorithm for grouping below will work if gigs with the same date appear consecutively. Knowing that the data is taken from a database this condition can be easily achieved by sorting by date.