Languages

JavaScript - how to group items in array by date?

0 points
Asked by:
Blythe-F
650

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
Answered by:
Blythe-F
650

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

  1. JavaScript - group / grouping array items with reduce method

References

  1. Array.prototype.reduce() - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join