Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter an array based on an object property [duplicate]

Tags:

javascript

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.

like image 467
Miguel Moura Avatar asked Feb 05 '16 18:02

Miguel Moura


People also ask

How do you filter duplicate objects in array?

To remove the duplicates from an array of objects:Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.

Which function removes duplicate values from an array?

Answer: Use the indexOf() Method You can use the indexOf() method in conjugation with the push() remove the duplicate values from an array or get all unique values from an array in JavaScript.

Does array filter create a copy?

filter() makes a new array, but it does not deep-copy the values from the original array. Array. filter doesn't clone anything, but it does create a new array.


2 Answers

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]);     } } 
like image 180
newfurniturey Avatar answered Sep 22 '22 22:09

newfurniturey


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

var filteredEvents = events.filter(function(event){     return event.date == '22-02-2016'; }); 
like image 30
leo.fcx Avatar answered Sep 20 '22 22:09

leo.fcx