32

I have an array of objects, something as follows:

var events = [
  { date: "18-02-2016", name: "event A" },
  { date: "22-02-2016", name: "event B" },
  { date: "19-02-2016", name: "event C" },
  { date: "22-02-2016", name: "event D" }
];

And I have a date, for example "22-02-2016". How can I get an array with all object which date is the same as the given date? So in this example I would get events B and D.

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

2 Answers2

39

You could use array's filter() function:

function filter_dates(event) {
    return event.date == "22-02-2016";
}

var filtered = events.filter(filter_dates);

The filter_dates() method can be standalone as in this example to be reused, or it could be inlined as an anonymous method - totally your choice =]

A quick / easy alternative is just a straightforward loop:

var filtered = [];
for (var i = 0; i < events.length; i++) {
    if (events[i].date == "22-02-2016") {
        filtered.push(events[i]);
    }
}
newfurniturey
  • 37,556
  • 9
  • 94
  • 102
  • What if I want to return all results that contain "2016", how should the function change? – Razvan Zamfir Jul 01 '20 at 14:26
  • @RazvanZamfir For that case, the `event.date == "..."` conditional would need to change to `event.date.includes('2016')` (alternatively, you could also use `.indexOf('2016')`) – newfurniturey Jul 01 '20 at 21:10
20

User Array.prototype.filter() as follows:.

var filteredEvents = events.filter(function(event){
    return event.date == '22-02-2016';
});
leo.fcx
  • 6,137
  • 2
  • 21
  • 37