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

$injector encountered a problem resolving the required dependency

Currently, I am attempting to adopt the LIFT protocol (Locate, Identify, Flat, Try(Dry)) for organizing my Angular projects. However, I am encountering difficulties in handling dependencies from other files. Here is the factory I have: (function () { ...

I am interested in utilizing props to send a variable to the view

Looking for assistance with passing the variable tmp_sell to my view. Here is the code: <p @tmp_sell="getTmpSell" >?</p> <input ref="q_subtotal" placeholder="Subtotal" @tmp_sell="getTmpSell" i ...

Cross-component communication in Angular

I'm currently developing a web-based application using angular version 6. Within my application, there is a component that contains another component as its child. In the parent component, there is a specific function that I would like to invoke when ...

Trouble encountered when utilizing jQuery for XML to HTML conversion and vice versa (CDATA mistakenly transformed into HTML comments)

I am in the process of developing a plugin/bookmarklet that is designed to extract an XML document from the <textarea> element on a web page, make modifications to the XML content, and then reinsert the updated version back into the <textarea> ...

Does Typescript fail to recognize the "delete" operator?

Whenever I utilize the delete operator in Typescript, it appears that the system does not recognize that the property has been eliminated. For instance: interface HasName { name: string; } interface HasNoName { name: never; } function removeName( ...

Exploring the depths of AngularJS through manual injection

I seem to have misunderstood the tutorial and am struggling to get manual injection working on my project. As I'm preparing to minify and mangle my JS code, I decided to manually inject all my modules and controllers. However, I keep encountering err ...

Modifying iframe src using click event from a separate component in Angular 10

I am looking to dynamically update the src attribute of an iframe when the menu bar is clicked. The menu bar resides in a separate component and includes a dropdown menu for changing languages. Depending on which language is selected, I want to update the ...

Tips for extracting variables from a querystring in Express?

I am trying to retrieve values sent to the server: "/stuff?a=a&b=b&c=c" Can you please advise me on how to extract these values using express? So far, I have attempted... app.get( "/stuff?:a&:b&:c", function( req, res ){}); ...but unfo ...

What is the solution to having a div move along with window resizing without displacing adjacent divs?

After much effort, I still can't seem to get this working correctly. I've been playing around with a section named "RightExtra" and a div inside it called "RightExtraContent". My goal is to allow these two divs to move freely when the window is ...

Extract data from a JSON-encoded array using JavaScript

I sent a JSON encoded array to JavaScript. Now I want to access that array to retrieve the different elements. When I print it out using console.log(), I see this array: array(1) { [16]=> array(2) { [3488]=> array(1) { [0]=> ...

What are the steps to execute PhantomJS on a client machine?

I have implemented an HTML to PDF converter that utilizes phantomjs, following this method: npm install -g html-pdf var fs = require('fs'); var pdf = require('html-pdf'); var html = fs.readFileSync('./test/businesscard.html' ...

Organizing outcome searches through ajax

I have a result table displayed on the left side https://i.stack.imgur.com/otaV4.png https://i.stack.imgur.com/pp9m0.png My goal is to transform it into the format shown on the right side of the table In a previous inquiry found here, @Clayton provided ...

Guide on efficiently navigating a website: utilize selenium python to effortlessly hover the mouse over a sub menu and click on desired options

Seeking to automate a web application called "Maximo" using Selenium in Python, I've successfully managed to log in with credentials and click on buttons. However, I'm stumped on how to hover the mouse over a submenu and perform a click action. ...

What causes TypeScript to automatically infer a default property when dynamically importing a JavaScript file that lacks a default export?

While dynamically importing a javascript file that exports multiple functions (without a default export), I encountered this issue: const sayHi = import('./sayHi.js') I was expecting the type of sayHi to be Promise<{name1: function, name2: fu ...

What is the best way to choose a single item from an array using jQuery?

Within an array, I have IDs and descriptions like: var tablica = [{"3":"asdasd asd"},{"19":"asddas fff"},{"111111":"adas asf asdff ff"},{"4":"re"},{"5":"asdasd"},{"6":"we"},{"7":"asdasdgg"},{"9":"asdasdasd"},{"16":"sdads"},{"10":"asdgg"},{"11":"ggg"}]; ...

jQuery uploadify encountered an error: Uncaught TypeError - It is unable to read the property 'queueData' as it is undefined

Once used seamlessly, but now facing a challenge: https://i.stack.imgur.com/YG7Xq.png All connections are aligned with the provided documentation $("#file_upload").uploadify({ 'method' : 'post', 'but ...

Transitioning JS/CSS effects when the window is inactive

My latest project involved creating a small slider using JavaScript to set classes every X seconds, with animation done through CSS Transition. However, I noticed that when the window is inactive (such as if you switch to another tab) and then return, the ...

How to Override package.json Scripts in NPM

Is it possible to modify package.json scripts without changing the original file? I need to customize the memory allocation for a specific step, but altering the package.json will affect everyone. For example, our current script is: "script": { "dev": ...

Difficulty in displaying title on navbar using ionic

I've been grappling with a challenge in angular and ionic where I can't seem to display any title in the navbar. My setup is quite intricate, involving multiple nested views. Here's the list of states: state('app', { cache: fal ...

What is the process for populating dropdown options from state?

I've been struggling to populate a select element with options based on an array in state. Despite trying various methods, the code snippet below seems to be the most detailed (I'm still getting familiar with React after taking a break for a few ...