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.
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.
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.
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.
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]); } }
User Array.prototype.filter() as follows:.
var filteredEvents = events.filter(function(event){ return event.date == '22-02-2016'; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With