Tips for sorting through and minimizing data based on the most recent date

info = {
 start: 1,
 data: [
  {
   name: 'Maria',
   date: '2020-02-15
  },
  {
   name: 'Paula',
   date: '2020-06-10
  },
  {
   name: 'Eva',
   date: '2020-12-05
  },
  {
   name: 'Sophia',
   date: '2021-03-21
  }
 ],
 totalRecords: 25
}

I am attempting to filter the information to show only the most recent date, which is 2021-03-21.

This is what I have tried:

response['data']['data'] = response['data']['data'].filter(item => {
           return item['date'] > '2021-03-21';
         });

However, it is not yielding the desired result.

The expected outcome should resemble this

info = {
 start: 1,
 data: [
  {
   name: 'Sophia',
   date: '2021-03-21'
  }
 ],
 totalRecords: 25
}

Answer №1

To retrieve the item with the most recent date, you can utilize the sort method followed by selecting the first element in the array.

data.data.sort((a, b) => new Date(b.date) - new Date(a.date))[0];

Answer №2

Various solutions may present certain challenges such as performance issues and unexpected outputs.

  1. Avoid using sort due to the potentially high time complexity of at least O(nlogn).
  2. Using filter could result in retrieving more than one lastItem.

==> Instead, consider utilizing Array#reduce with a time complexity of just O(n), like so:

const comparedDate = new Date('2020-04-01')
const response = {
 start: 1,
 data:[{name:'Juan',date:'2020-01-19'},{name:'Carlo',date:'2020-03-01'},{name:'Dela',date:'2020-03-01'},{name:'Cruz',date:'2021-04-01'}],
 totalRecords:19};

const lastData = response.data.reduce((acc, curr) => {
  if(new Date(curr.date) > comparedDate)
    acc = curr;
  
  return acc;
}, response.data[0]);

console.log(lastData);

If you require multiple items with dates <= 2020-04-01, you can achieve this by:

const comparedDate = new Date('2020-04-01')
const response = {
 start: 1,
 data:[{name:'Juan',date:'2020-01-19'},{name:'Carlo',date:'2020-03-01'},{name:'Dela',date:'2020-03-01'},{name:'Cruz',date:'2021-04-01'}],
 totalRecords:19};

response.data = response.data.reduce((acc, curr) => {
  if(new Date(curr.date) >= comparedDate)
    acc.push(curr);
  
  return acc;
}, []);
console.log(response);

Answer №3

To properly handle the dates in this scenario, it is necessary to transform the date strings into Date objects.

const checkDate = new Date('2020-04-01')
const response = {
 start: 1,
 data: [
  {
   name: 'Juan',
   date: '2020-01-19'
  },
  {
   name: 'Carlo',
   date: '2020-03-01'
  },
  {
   name: 'Dela',
   date: '2020-03-01'
  },
  {
   name: 'Cruz',
   date: '2021-04-01'
  }
 ],
 totalRecords: 19
}

response.data = response
  .data
  .filter(({date}) => new Date(date) > checkDate)
  
console.log(response)

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

Develop a fresh button using either JavaScript or PHP

I have designed a mini cart (drop down) on my WordPress site with different styles for when there are products and when empty. To enhance the design, I have utilized CSS pseudo elements before and after to add content dynamically. Is it possible to includ ...

How to display and retrieve data from a JSON object using JavaScript

Having trouble retrieving input values from a JSON object and getting 'undefined' when running the code. Any suggestions or ideas would be greatly appreciated as I have tried various approaches. Additionally, I need to utilize JSON for my school ...

"Which is better for maximizing the efficiency of an image grid: CSS or Jquery? What are the key

As a UX Designer looking to enhance my coding skills, I must admit my code may not be perfect. Please bear with me as I navigate through this process. I am in the process of revamping my portfolio website. The original seamless grid was created using a Ma ...

Displaying a JQuery notification when hovering over a link

I am having trouble getting an alert to pop up when I hover over a hyperlink using JQuery and Javascript. The hyperlink is inside an anchor within the main section of the HTML. Any assistance would be much appreciated. Here is my current code snippet: &l ...

Vue js lacks the ability to effectively link HTML elements to corresponding JavaScript functions

I seem to be missing a crucial element in my spring boot application. I am attempting to follow the initial steps outlined in the Vue documentation to create the most basic Vue application possible. Here is what I currently have: @Controller public class ...

Creating interactive JavaScript elements that can be moved around within a container

I recently faced a challenge while attempting to make draggable elements within a div. The issue arose when I realized that I couldn't figure out how to drag each element individually without affecting the others. My current code only allows for handl ...

What is the method for determining the level based on the provided experience points?

I've created a formula that can calculate experience based on specific levels and another formula that calculates the level based on given experience. However, there seems to be an issue with the second function as it is not returning the expected val ...

Emulating user interaction using Prototype library - Simulate.js

I have set up a Prototype code to act as an observer, but I am facing issues triggering the observer after manually setting the value of the select element... select.observe('change', this.onChange.bindAsEventListener(this)); Initially, I tried ...

Instead of loading the HTML into the div, Ajax is now sending me the link instead

I have just begun working on a new laravel project and am currently working on the user profile page, which will include a sidebar with links like Portfolio, Account Settings, etc. My goal is to dynamically load each page into a div when a link in the side ...

What could be causing Express to display a different page than the one specified in res.render?

Upon trying to view the compare.ejs page, I encountered an unexpected issue where a different page was being rendered instead. What could be causing this discrepancy? Here is my app.js code: var compare = require('./routes/compare')(nav); app.u ...

The React task list updates the todo items on change, rather than on submission

As a newcomer to React, I have embarked on the classic journey of building a todo app to learn the ropes. Everything seems to be functioning smoothly except for one minor hiccup: When I input a new todo and hit "submit", it does get added to my array but d ...

javascript/jquery form validation problems/support needed (jQuery)

Long story short, I am facing an issue with my code and seeking some guidance. I have various functions to perform different checks. For this particular example, I have a form with a default value of "enter name here" for one field. Here is the HTML snipp ...

HTML text not lining up with SVG text

Why is the positioning of SVG Text slightly off when compared to CSS text with the same settings? The alignment seems awkwardly offset. Any help in understanding this would be much appreciated! Even with x: 50% and the relevant text-anchor property set to ...

Error encountered with tsc-generated .d.ts files stating "Namespace 'Jimp' not found"

Currently, I am in the process of developing an NPM package, and within my codebase lies a specific class that looks like this: import { MIME_PNG } from 'jimp'; import { IDimensions } from './spritesheet'; /** * Representing a single ...

Using *ngIf to construct SVG icons in Angular 2 doesn't contribute to the DOM in any way

I am currently utilizing icoMoon to import a series of SVG icons. The structure of the html I'm trying to create using ngIf is as follows: <div class="contactIcon"> <svg class="icon icon-envelop"> <use xlink:href="symbol-d ...

Exploring Child Types in Typescript and JSX minus the React framework

It seems like there's a missing piece of the puzzle that I can't quite figure out. Despite going through the documentation on JSX in non-React settings, I'm still unable to spot my mistake. Let's examine the following code: /** @jsx pra ...

Tips for changing the TextField variant when it receives input focus and keeping the focus using Material-UI

When a user focuses on the input, I'd like to change the variant of the TextField. The code snippet below accomplishes this, but the input loses focus. This means the user has to click again on the input to focus and start typing. import React, { useS ...

Using PHP to access a property using json_decode

Hello, I am attempting to access certain properties using json_decode, but I am encountering issues. Specifically, I am interested in retrieving the values for userRating and pressRating properties. $result_json = json_decode($result, true); echo $result_j ...

Using AngularJs, you can access the document.body.onfocus event within the controller of

I am attempting to detect when the user closes or cancels the File Upload Window <input type="file"> Since there isn't a built-in listener for the close event of the file upload, I am trying to capture it using the document.body.focus event, s ...

Using a function as an argument to handle the onClick event

I have a function that generates a React.ReactElement object. I need to provide this function with another function that will be triggered by an onClick event on a button. This is how I call the main function: this._createInjurySection1Drawer([{innerDra ...