search

Home  >  Q&A  >  body text

Filter array based on object properties

I have an array of objects as shown below:

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" }
];

I have a date, for example "22-02-2016". How to get an array of all objects whose date is the same as a given date? So in this example I'm going to get events B and D.

P粉331849987P粉331849987386 days ago436

reply all(2)I'll reply

  • P粉771233336
  • P粉489081732

    P粉4890817322024-01-30 09:39:20

    You can use the filter() function of the array:

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

    filter_dates() Methods can be standalone, reused as in this example, or inline as anonymous methods - the choice is entirely yours =]

    A quick/easy alternative is a simple loop:

    var filtered = [];
    for (var i = 0; i < events.length; i++) {
        if (events[i].date == "22-02-2016") {
            filtered.push(events[i]);
        }
    }

    reply
    0
  • Cancelreply