Find the object in an array that has the most recent date property

Suppose I have an array of objects like this :

let sampleArray = [
  {
    "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
  }];

Can you suggest a way to filter this array so that only the object with the latest date property is returned?

Answer №1

Utilize the power of Array#reduce and retrieve the object with the most recent date (since you have an ISO date, direct comparison is possible):

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>');

Answer №2

Utilize the sort function for this task:

To accomplish this without checking for null values, you can simply execute

array.sort((a,b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())[0];

Answer №3

Give this a shot:

array.sort(function(item1, item2) {
        return Date.parse(item1.date) - Date.parse(item2.date);
   });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Django with Ajax without the need for the JQuery library

Exploring the world of Ajax without jQuery Library has been quite a journey. I recently created a basic view that displays a random number on the screen. After adding a button and invoking the ajax function, I encountered an issue where clicking the button ...

Ways to retrieve a variable from outside of a function

I am in need of sending the following batch data to the database, but I am facing difficulties in including the course_id along with the batchData. Currently, I am retrieving the course_id from another service that fetches data from a course table. I am ...

Issue regarding navigation using nuxt-links to pages with hashtags/anchors

When it comes to my website navigation, I rely on nuxt-links a lot. Most of these links direct users to specific sections within the home page using hashes like: <nuxt-link v-else class="text-link" :to="localePath('index') + #hash" > ...

What is the best way to transfer an array made in JavaScript to a different JSP and subsequently utilize that array in a Java function within that JSP?

I have a script that needs to pass an array called "playernames" to a Java function on another .jsp. I'm looking for guidance on how to send this array to the other page and then retrieve it for my Java function. <script> function getPlayerName ...

Having trouble getting my app.get calls to work in the new Node Express project

Recently, I kicked off a new project and encountered a perplexing issue - my app.get method simply refuses to be invoked. The site keeps loading indefinitely without any content being displayed. Initially, I copied and pasted the code from another project ...

What is the best way to implement jQuery after new elements have been added to the DOM?

I'm currently working on a Sentence Generator project. The program is designed to take a list of words and retrieve sentences from sentence.yourdictionary.com based on those words. The first sentence fetched from the website is displayed using the cod ...

What is the process of encoding a String in AngularJS?

Utilizing Angularjs for sending a GET HTTP request to the server, which is then responded to by the Spring MVC framework. Below is a snippet of code depicting how the URL is built in Angular: var name = "myname"; var query= "wo?d"; var url = "/search/"+qu ...

Switch the scroll direction in the middle of the page and then switch it back

Yesterday, while browsing online, I stumbled upon this website and was amazed by the unique scroll direction change from vertical to horizontal mid-page. I'm curious about how they managed to achieve that effect. Does anyone have insight into the pro ...

When I click the button, the page goes blank and keeps loading endlessly

http://jsfiddle.net/iansan5653/7EPjH/17/ <head> <script type='text/javascript' src='https://www.google.com/jsapi'></script> <script type="text/javascript"> function chart() { var pressure; ...

Enhancing the appearance of individual cells in jQuery DataTables

While working with jQuery DataTables, I have successfully managed to access row data and apply styling to the entire row. Below is the code snippet used to initialize the datatable: var $dataTable = $('#example1').DataTable({ "data": data, ...

Updating the columns in a row by clicking the refresh button with ajax in a JSP file

Hey there! I have a table on my JSP page with refresh buttons at the row level. When I click the refresh button, it should check the database and update those two columns with new values. Below is the code snippet for my JSP page: <script src="js/jque ...

Struggling to determine whether an array contains data or is void in ReactJS?

In the state, I have an array and I set the default value of my state to an empty array []. After loading an API request, I need to display a loader until the data is ready. So, I am using a condition like this: (if the array length === 0, the loader wil ...

Tips for successfully passing multiple properties to a function in React

<DeleteForeverIcon className={classes.deleteHwIcon} onClick={() => { deleteHomework(value.name, value.class); }} /> I'm looking to modify the function deleteHomework so that it can receive two properties instead of just one. In add ...

What is the correct way to send an HTTP error code to an error handling middleware?

Currently, I am in the process of developing a RESTful API using node.js and express framework. I would like to create a single error handling middleware for this project. The approach I am currently considering involves: router.get('/some-resource&a ...

Refreshing a DIV in Rails by reloading from model using a JavaScript function

Recently, I created a page displaying the number of Widgets a customer has. Below is the view written in Haml: #available = "Available widgets: #{@customer.widgets.unused.count()}" (The "unused" scope in the model displays available widgets). When a C ...

Exploring the (*ngFor) Directive to Iterate Through an [object Object]

Attempting to iterate through the array using *ngFor as shown below. let geographicalArea = [{ "_id": "5e77f43e48348935b4571fa7", "name": "Latin America", "employee": { "_id": "5e77c50c4476e734d8b30dc6", "name": "Thomas", ...

Integrating custom HTTP headers with window.location.href in an Angular application

I encountered a situation with my Angular app where I needed to redirect it to a non-angular HTML page. My initial thought was to use $window.location.href to achieve this redirection successfully. However, the challenge arose when I realized that my Node. ...

Unexpected behavior encountered when implementing specific Textfield validation with Material UI

Currently running a project on Node and utilizing React for the front-end, I have encountered an issue with setting .env variables. The project is built with Material UI, and most TextFields are working as expected with their specified validation rules. ...

Unable to establish a connection with the endpoint

I'm encountering an issue while trying to connect to the endpoint on the server. Below is the code snippet: Register.jsx function Register() { const [registerUser, setRegisterUser] = useState({ username: "", email: "", password: "", ...

An issue arose while trying to create the perfect seed with yeoman

While working on my first Yeoman webapp using the ultimate-seed-generator, I encountered some errors that are hindering progress: C:\Users\Fidel\Desktop\Nueva carpeta\new-proyect>npm install > <a href="/cdn-cgi/l/email ...