Feeling a bit puzzled by my title,
Here's the issue at hand - I aim to destructure an array of objects to utilize its properties in a chartJS Line Graph.
Take a look at the replicated array below:
[{
"page": "Page 1",
"date": "2021-10-05",
"visitors": 10
}, {
"page": "Page 2",
"date": "2021-10-05",
"visitors": 20
}, {
"page": "Page 3",
"date": "2021-10-05",
"visitors": 30
},{
"page": "Page 1",
"date": "2021-10-04",
"visitors": 40
}, {
"page": "Page 2",
"date": "2021-10-04",
"visitors": 50
}, {
"page": "Page 3",
"date": "2021-10-04",
"visitors": 60
}]
Each entry consists of a date (date), number of visitors (visitors), and a page name (page)
For instance, if there are 2 dates and 3 pages, seeking to retrieve the visitor numbers per date per page will result in 6 entries (3 pages for each date) as shown in the example above.
How can I gather the visits for each page and create an array that contains unique page names & dates just once along with the corresponding visit numbers like:
[ {
page: pageName,
dates: [],
numberOfVisits: [],
},
{
page: pageName,
dates: [],
numberOfVisits: [],
},
{
page: pageName,
dates: [],
numberOfVisits: []
},
]
I attempted to streamline the array and filter it based on either dates or page names like so:
myArray.reduce((a, c) => {
/* Filtering by date - only one page name is returned */
let filtered = a.filter(el => (el.date === c.date));
/* Alternatively, filtering by page name - results in only one date for each */
/* let filtered = a.filter(el => (el.page === c.page)); */
if (filtered.length > 0) {
/* Summing up the number of visits - this method works in both scenarios */
a[a.indexOf(filtered[0])].m_unique_visitors += +c.m_unique_visitors;
} else {
a.push(c);
}
})
return a;