How can I retrieve the most recent date from a collection of hashes and then extract the corresponding name key/value pair?

I am dealing with an array of hashes structured like this:

[
 {
  "Address": 25,
  "AlertType": 1,
  "Area": "North",
  "MeasureDate": "2019-02-01T00:01:01.001Z",
  "MeasureValue": -1
 },
{
  "Address": 26,
  "AlertType": 1,
  "Area": "West",
  "MeasureDate": "2016-04-12T15:13:11.733Z",
  "MeasureValue": -1
},
{
  "Address": 25,
  "AlertType": 1,
  "Area": "North",
  "MeasureDate": "2017-02-01T00:01:01.001Z",
  "MeasureValue": -1
}
      .
      .
      .
]

My task is to identify the most recent date in the array and return the corresponding Address value. I have successfully found the newest date using the following code:

let newest = new Date(Math.min.apply(null, data.map(function(e) {
  return new Date(e.created_at);
})));
most_recent = newest;

However, I am struggling to retrieve the Address value. The code I've written only returns the date or address from the

let findEarliest = (name) => {
  let nameIndex = 0;
  data.forEach((date) => {
    if(date.created_at.includes(most_recent));
      nameIndex = data.indexOf(date);
  });
  return data[nameIndex].name;
};

Any assistance on this issue would be greatly appreciated.

Answer №1

Give this a try. It organizes the hash array based on MeasureDate and then retrieves the address of the first element.

const hash = [
   {
  "Address": 1,
  "AlertType": 1,
  "Area": "North",
  "MeasureDate": "2010-02-01T00:01:01.001Z",
  "MeasureValue": -1
 },
 {
  "Address": 25,
  "AlertType": 1,
  "Area": "North",
  "MeasureDate": "2019-02-01T00:01:01.001Z",
  "MeasureValue": -1
 },
{
  "Address": 26,
  "AlertType": 1,
  "Area": "West",
  "MeasureDate": "2016-04-12T15:13:11.733Z",
  "MeasureValue": -1
},
{
  "Address": 20,
  "AlertType": 1,
  "Area": "North",
  "MeasureDate": "2017-02-01T00:01:01.001Z",
  "MeasureValue": -1
}
]

const latestAddress = hash.sort((a, b) => b.MeasureDate > a.MeasureDate)[0].Address

console.log(latestAddress)

Answer №2

Here is a code snippet that may be useful:

Updated on 08/17/2017:

RobG recommended this code as the most optimal solution.

Optimal solution:

const lastAddresDetails = addressList.sort((a, b) => b.MeasureDate.localeCompare(a.MeasureDate))[0];

console.log(lastAddresDetails.Address)

Alternative approaches:

const lastAddresDetails = addressList.sort((a, b) => b.MeasureDate > a.MeasureDate)[0];

console.log(lastAddresDetails.Address)

or

var lastAdressDetails = addressList.sort(function (a, b) {
            return b.MeasureDate > a.MeasureDate;
        })[0];

console.log(lastAdressDetails.Address);

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

What is the best way to clear an array?

Yesterday I had a query regarding JSON Check out this link for details: How to return an array from jQuery ajax success function and use it in a loop? One of the suggested answers included this script: setInterval(updateTimestamps,30000); var ids = new ...

Loading Embedded Content with ReactJS

Currently, I am developing a one-page website with ReactJS. Each section of the site is created as individual React components, which are displayed conditionally based on the user's tab selection in the navigation bar. As part of my design, I have in ...

Capture microphone and audio in a SIP call with sip.js

Greetings Stack Overflow community! I am in need of assistance with a project involving sip.js and VoIP for making real phone calls. The Objective I aim to enable users to record audio from both parties during a call and save the data on a server (either ...

Is there a constraint on JSON data?

Is there a limit to the amount of data that JSON with AJAX can handle in outgoing and returning parameters? I am trying to send and receive a file with 10,000 lines as a string from the server. How can I accomplish this task? Can a single parameter manage ...

Refresh in AJAX, automated loading for seamless transition to a different page

Having an issue with the page not auto-refreshing, although it loads when I manually refresh. P.S Loading the page onto another page. Below is my HTML and AJAX code along with its database: The Trigger Button <?php $data = mysqli_query ...

Java: Functions Not Running As Expected

Having some issues with the three user-defined methods and correctly calling them within the main method. No syntax errors are present, so the problem may lie in logical errors. The parameters also seem to be in order. This program is designed to check if ...

Can you please provide the Jquery alternative to this?

Can you provide a sleek jQuery solution for this problem? $('A').append(str); ...

Modify Chartjs label color onClick while retaining hover functionality

Currently, I have implemented vue-chart-js along with the labels plugin for a donut chart. Everything is working well so far - when I click on a section of the donut chart, the background color changes as expected. However, I now want to also change the fo ...

A comprehensive guide on utilizing the loading.tsx file in Next JS

In the OnboardingForm.tsx component, I have a straightforward function to handle form data. async function handleFormData(formData: FormData) { const result = await createUserFromForm( formData, clerkUserId as string, emailAddress a ...

AngularJS controller containing a nested app

Is there a way to implement this structure using AnglularJS? <body ng-app="mainBodyAppWrapper"> <div ng-controller = "mainBodyController"> <div ng-app="myApp"> <div ng-controller="controller3"> ...

Tips for updating mongoose user data with associated posts that share the same user id

As I dive into building my inaugural MERN application, a particular issue has arisen. The posts within the application contain the user id information: { "reward": { ... }, "_id": "5eb2d90d7d56c415cc4d5f97", "user": "5eabbb85b8814 ...

Having trouble getting OrbitControls to function properly in Object-Oriented Programming (OOP)

Exploring the world of THREE.js and Object-oriented JavaScript. Here's the code I'm working with: https://gist.github.com/BobWassermann/581492be11db361c39ee While my browser is showing the correct output, I'm having trouble getting the Orb ...

Issue: React child must be a valid object - Runtime Error Detected

As I delve into the world of React, NextJs, and TypeScript, I stumbled upon a tutorial on creating a navbar inspired by the 'Strip' style menu. It has been quite a learning journey for me as a newbie in these technologies. After seeking help for ...

Tips for splitting a container of specific height into sections measuring 80% and 20%

I am working on a container with a fixed position that I want to split into two halves: 80% and 20% at the bottom. This is what I want it to look like: Click here to see the image. Note: The layout should adjust itself when the window is resized. You c ...

Struggling to remove the image tag from the jQuery ajax response

My web app is designed to send an ajax post request to a PHP script, which then returns a chunk of HTML data. This HTML includes an image and a table of information. The challenge I'm facing is how to extract the image from the rest of the HTML so tha ...

Tips for seamlessly playing flowplayer while an mp4 file is loading?

Is there a way for the video to play while it is buffering, rather than waiting for the mp4 to be fully loaded? Thank you. ...

Is there a better approach to verifying an error code in a `Response` body without relying on `clone()` in a Cloudflare proxy worker?

I am currently implementing a similar process in a Cloudflare worker const response = await fetch(...); const json = await response.clone().json<any>(); if (json.errorCode) { console.log(json.errorCode, json.message); return new Response('An ...

Issue: why is EPIPE being written on sendFile()?

Utilizing the html-pdf module for PDF generation, the code snippet below is what I am using: var ejs = require('ejs'); var fs = require('fs'); var pdf = require('html-pdf'); var build = function (template, data) { var ht ...

Angular encountered an issue with an HTTP POST request, as the 'Access-Control-Allow-Origin' header was not found on the requested resource

I have been attempting to transmit data to a servlet using Angular HTTP POST requests. var httpPostData = function (postparameters, postData){ var headers = { 'Access-Control-Allow-Origin' : '*', &a ...

Effective ways to retrieve API response data in React JS

I am working on a Spring Boot project which includes an API for user login. When the user name and password are sent through this API, it checks the database for the information. If the data is found, it returns a successful login message; otherwise, it ...