TheWebs TheWebs - 3 months ago 8
Javascript Question

Give me all elements in the array that have the same date, JS

So consider the following data:

{
post_views:[
{
id:1,
post_id:5,
ip_address:"xxx",
created_at:"2016-08-08T22:22:45+0000",
updated_at:"2016-08-08T22:22:45+0000"
},
{
id:2,
post_id:5,
ip_address:"yyy",
created_at:"2016-08-08T22:23:00+0000",
updated_at:"2016-08-08T22:23:00+0000"
},
...
]
}


How would get I get all elements that match: 2016-08-08 ??

What have you tried?

Lodashes, filter:

let datesThatMatch = filter(this.state.data.post_views, (views) => {
return moment(views.created_at).format('MMMM Do YYYY') === moment(views.created_at).format('MMMM Do YYYY')
});

console.log(datesThatMatch);


I don't care about what time of day they were created at, just as long as the day they were created on match.

help?

Update



I just realized I am also going about this all wrong because while I only showed you a portion of the data, there are hundreds of these objects i the array (if not thousands) and the goal is to say, ok there are 16 matches for 2016-08-08, 50 matches for x date, 14 matches for y date which adds to the complexity of this filter.

Answer

I think groupBy is a better alternative based on your update:

var data = {  
   post_views:[  
      {  
         id:1,
         post_id:5,
         ip_address:"xxx",
         created_at:"2016-08-08T22:22:45+0000",
         updated_at:"2016-08-08T22:22:45+0000"
      },
      {  
         id:2,
         post_id:5,
         ip_address:"yyy",
         created_at:"2016-08-08T22:23:00+0000",
         updated_at:"2016-08-08T22:23:00+0000"
      },
      {  
         id:3,
         post_id:5,
         ip_address:"zzz",
         created_at:"2016-08-12T20:15:00+0000",
         updated_at:"2016-08-12T21:20:00+0000"
      },
   ]
}
     
let groupedDatesThatMatch = _.groupBy(data.post_views, function(views) {
     return moment(views.created_at).format('MMMM Do YYYY')
});
     
console.log(groupedDatesThatMatch);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.2/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>

You get an object of arrays out the other end

Comments