EN
JavaScript - how to group items in array by date?
1
answers
0
points
How can I group items in array by date property value?
I have the following array of data:
var data = [
{ id: 1, date: '2022-11-03T22:00:00+00:00' },
{ id: 2, date: '2022-12-03T22:00:00+00:00' },
{ id: 3, date: '2022-11-03T22:00:00+00:00' },
{ id: 4, date: '2022-12-03T22:00:00+00:00' },
{ id: 5, date: '2022-12-03T22:00:00+00:00' },
];
I would like to group the items into 2 groups: 2022-11-03 and 2022-12-03.
1 answer
0
points
I highly recommend to read this article from which the solution below was taken.
For your data the solution would be:
// ONLINE-RUNNER:browser;
function groupItems(array, property) {
return array.reduce(function(groups, item) {
var name = item[property]
var group = groups[name] || (groups[name] = []);
group.push(item);
return groups;
}, { });
}
// Usage example:
var array = [
{id: 1, date: '2022-11-03T22:00:00+00:00'},
{id: 2, date: '2022-12-03T22:00:00+00:00'},
{id: 3, date: '2022-11-03T22:00:00+00:00'},
{id: 4, date: '2022-12-03T22:00:00+00:00'},
{id: 5, date: '2022-12-03T22:00:00+00:00'}
];
var groups = groupItems(array, 'date'); // array will be grouped by 'date' property
for(var key in groups) {
var group = groups[key];
console.log('"' + key + '"\t' + JSON.stringify(group, null, 4))
}
See also
References
0 comments
Add comment