Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

group by Date in Javascript

I have an array of birthdays

const birthdays = [
    {name: 'John', birthday: '08-08-1960'},
    {name: 'James', birthday: '08-25-1960'},
    {name: 'Mary', birthday: '01-01-1990'},
]

and I need to generate a new array with the birthdays grouped by month-year

const grouped = [
    {'08-1960': [
        {name: 'John', birthday: '08-08-1960'},
        {name: 'James', birthday: '08-25-1960'},        
    ]},
    {'01-1990': [
        {name: 'Mary', birthday: '01-01-1990'}, 
    ]},
]

I was looking at something like this. using moment and lodash

let groupedResults = _.groupBy(results, (result) => moment(result['Date'], 'DD/MM/YYYY').startOf('isoWeek'));

but I can´t imagine how to generate the new array structure (with the month-year as keys) thank you.

update: it should return an array not an object :facepalm

like image 312
handsome Avatar asked May 20 '26 11:05

handsome


1 Answers

You can use reduce()

  • Apply reduce() on array of object and set accumulator to empty object {}
  • Then split() birthday by - and get only get first and third element.
  • If the key exist is accumulator that concat() new value to it. Otherwise concat() it to empty array [] and then set it as property of accumulator.

const arr = [
    {name: 'John', birthday: '08-08-1960'},
    {name: 'James', birthday: '08-25-1960'},
    {name: 'John', birthday: '01-01-1990'},
]

let res = arr.reduce((ac,a) => {
 let key = a.birthday.split('-');
 key = `${key[0]}-${key[2]}`;
 ac[key] = (ac[key] || []).concat(a);
 return ac;
},{})
res = Object.entries(res).map(([k,v]) => ({[k]:v}))
console.log(res)
like image 146
Maheer Ali Avatar answered May 22 '26 23:05

Maheer Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!