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.

2

2 Answers 2

41

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]);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

What if I want to return all results that contain "2016", how should the function change?
@RazvanZamfir For that case, the event.date == "..." conditional would need to change to event.date.includes('2016') (alternatively, you could also use .indexOf('2016'))
21

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

var filteredEvents = events.filter(function(event){
    return event.date == '22-02-2016';
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.