Filter array based on object properties
P粉331849987
P粉331849987 2024-01-29 10:36:17
0
2
351

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粉331849987
P粉331849987

reply all(2)
P粉771233336

UserArray.prototype.filter() is as follows:.

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

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 
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!