If I have an object array like this :
var array = [
{
"id": 5,
"date": "2016-01-15T16:18:44.258843Z",
"status": "NEW",
"created_at": "2016-01-29T13:30:39.315000Z",
"updated_at": "2016-01-29T13:30:39.315000Z",
"request": 4
},
{
"id": 6,
"date": "2016-01-19T16:18:44.258843Z",
"status": "STD",
"created_at": "2016-01-29T13:30:39.372000Z",
"updated_at": "2016-01-29T13:30:39.372000Z",
"request": 4
},
{
"id": 7,
"date": "2016-01-23T16:18:44.258843Z",
"status": "FOR",
"created_at": "2016-01-29T13:30:39.417000Z",
"updated_at": "2016-01-29T13:30:39.417000Z",
"request": 4
}];
how can I filter it in order to only return the element (object) with the latest property date
?
One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.
You can use the array_filter() function to filter multidimensional array by date range using PHP. This example will show you how to filter array by specific date range in PHP. The following code snippet helps to filter last month events from an array using the array_filter() and strtotime() function in PHP.
To filter an array of objects in React:Call the filter() method on the array. On each iteration, check if a certain condition is met. The Array. filter methods returns an array with all elements that satisfy the condition.
Just use Array#reduce and return the object with the latest date (while you have an ISO date, you can compare it directly):
var array = [{ "id": 5, "date": "2016-01-15T16:18:44.258843Z", "status": "NEW", "created_at": "2016-01-29T13:30:39.315000Z", "updated_at": "2016-01-29T13:30:39.315000Z", "request": 4 }, { "id": 6, "date": "2016-01-19T16:18:44.258843Z", "status": "STD", "created_at": "2016-01-29T13:30:39.372000Z", "updated_at": "2016-01-29T13:30:39.372000Z", "request": 4 }, { "id": 7, "date": "2016-01-23T16:18:44.258843Z", "status": "FOR", "created_at": "2016-01-29T13:30:39.417000Z", "updated_at": "2016-01-29T13:30:39.417000Z", "request": 4 }],
latest = array.reduce(function (r, a) {
return r.date > a.date ? r : a;
});
document.write('<pre>' + JSON.stringify(latest, 0, 4) + '</pre>');
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