-4

I'am trying to solve an issue that requires the sort of an array of objects containing information. For example, transform this:

[
{ 
  name: 'test1',
  date: '2019-02-18T08:33:01.000Z',
},
{ 
  name: 'test2',
  date: '2019-02-19T08:33:01.000Z',
},
{ 
  name: 'test3',
  date: '2019-02-19T08:33:01.000Z',
},
]

To this:

{
 '2019-02-18':{
   name: 'test1'
},
 '2019-02-19':[
 {
   name: 'test2',
 },
 {
   name: 'test3',
 }
]
}

How can i achieve this?

  • 4
    Possible duplicate of [Most efficient method to groupby on a array of objects](https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-a-array-of-objects) – Luca Kiebel Feb 18 '19 at 21:16
  • 2
    We would be happy to help you, but we are less keen on doing work *for* you. Please share with us what you have so far, so we can help you get it working. Thanks. –  Feb 18 '19 at 21:18

2 Answers2

0

Assuming you want an array of objects for every grouped date. One alternative is to use Array.reduce() in conjunction with String.match()

const input = [
  {name: 'test1', date: '2019-02-18T08:33:01.000Z'},
  {name: 'test2', date: '2019-02-19T08:33:01.000Z'},
  {name: 'test3', date: '2019-02-19T08:33:01.000Z'}
];

let res = input.reduce((acc, {name, date}) =>
{
    let [m, d] = date.match(/(.+)T/);
    acc[d] = [...(acc[d] || []), {name}];
    return acc;
}, {});

console.log(res);
Shidersz
  • 16,846
  • 2
  • 23
  • 48
-1

This is more a group by problem than a sort. Object keys are unsorted, also.

function groupByDate(data) {
  let result = {};
  
  data.forEach((el) => {
    let datePart = el.date.split("T")[0];
    let value = result[datePart]
    if(value) {
      result[datePart].push({name: el.name})
    } else {
      result[datePart] = [{name: el.name}]
    }
  });
  
  return result;
}


var dates = [
{ 
  name: 'test1',
  date: '2019-02-18T08:33:01.000Z',
},
{ 
  name: 'test2',
  date: '2019-02-19T08:33:01.000Z',
},
{ 
  name: 'test3',
  date: '2019-02-19T08:33:01.000Z',
},
];

console.log(groupByDate(dates));
Jonathan Hamel
  • 1,393
  • 13
  • 18