Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter object array to return the object with the latest date property

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 ?

like image 356
Ellone Avatar asked Feb 04 '16 13:02

Ellone


People also ask

How do you filter an object in an array?

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.

How do you filter dates in arrays?

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.

How do you filter an array of objects in react?

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.


1 Answers

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>');
like image 60
Nina Scholz Avatar answered Nov 04 '22 15:11

Nina Scholz