-1

I have some data like these:

[
  {
    startTime: '2020-01-28T11:00:00',
    name: 'John',
  },
  {
    startTime: '2020-01-28T12:00:00',
    name: 'Doe'
  },
  {
    startTime: '2020-01-29T10:00:00',
    name: 'javascript',
  }
]

As you see I got same days in some objects and now I want to filter them by day! All the same days be into an array.

Be like this:

[
  {
    startTime: '2020-01-28T11:00:00',
    name: 'John'
  },
  {
    startTime: '2020-01-28T12:00:00',
    name: 'Doe'
  },
],
[
  {
    startTime: '2020-01-29T10:00:00',
    name: 'javascript'
  },
]

Do you have any suggestion or advice?

Amir
  • 49
  • 5

1 Answers1

2

You can create a groupBy function like this for the same

We group players by substring of first 10 characters in startTime which will be the data of same

var players = [
    {
      startTime: '2020-01-28T11:00:00',
      name: 'John',
    },
    {
      startTime: '2020-01-28T12:00:00',
      name: 'Doe'
    },
    {
      startTime: '2020-01-29T10:00:00',
      name: 'javascript',
    }
  ]
  
  var groupBy = function(xs, key) {
    return xs.reduce(function(rv, x) {
      (rv[x[key].substr(0,10)] = rv[x[key].substr(0,10)] || []).push(x);
      return rv;
    }, {});
  };
  
  console.log(Object.values(groupBy(players, 'startTime')));
Sarfraaz
  • 1,273
  • 4
  • 15