handsome
handsome

Reputation: 2392

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

Upvotes: 3

Views: 2204

Answers (2)

Maheer Ali
Maheer Ali

Reputation: 36564

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)

Upvotes: 3

Ramon Portela
Ramon Portela

Reputation: 409

As explained here https://www.dyn-web.com/javascript/arrays/associative.php you can create arrays where the indexes are strings, but i won't work as a normal array.

Here is a snippet for doing what you want.

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

    const grouped = birthdays.reduce((prev, cur) => {

    	const date = new Date(cur.birthday);
    	const key = `${(date.getMonth() + 1)}-${date.getFullYear()}`;

    	if(!prev[key]){
    		prev[key] = [ cur ];
        }
    	else{
    		prev[key].push(cur);
        }

    	return prev;
    }, []);

    for(let i in grouped){
      console.log(grouped[i]);
    }

Upvotes: 0

Related Questions