Ways to select elements from an array of objects based on date

I'm currently working on a task that involves filtering an array of objects to find the ones closest to today. Unfortunately, I encountered an issue where the code is returning dates in June instead of May. Here's the snippet of code I've been using:

const findClosest = (data, accessor, target = Date.now()) =>
  data.reduce((prev, curr) => {
    const a = Math.abs(accessor(curr).getTime() - target);
    const b = Math.abs(accessor(prev).getTime() - target);
    return a - b < 0 ? curr : prev;
  });

const getClosestFromDate = (array, key, date) => {
  let arr = array.filter((e) => e[key] == date);
  return arr;
};

const sampleData = [{
    "max_retries_reached": 0,
    "next_charge_scheduled_at": "2022-06-23T00:00:00",
  },
  // additional object data here...
];

const processDateString = (dateString) => {
  let date = new Date(dateString);
  let year = date.getFullYear();
  let month = date.getMonth();
  console.log(date.toString());
  return new Date(year, month + 1, date);
};

const closest = findClosest(sampleData, ({
  next_charge_scheduled_at
}) => processDateString(next_charge_scheduled_at), "2022-05-10T03:03:42");

console.log(closest.next_charge_scheduled_at);

console.log(getClosestFromDate(sampleData, "next_charge_scheduled_at", closest.next_charge_scheduled_at));

I came across this piece of code while looking at solutions for similar questions. Despite my attempts to adjust the month variable, I haven't been able to retrieve the correct date. Any assistance you can offer would be greatly appreciated.

Answer №1

You were unnecessarily complicating things for yourself:

(My answer has been updated after reading the latest comment from OP.)

The constant acc represents a utility function(obj) that extracts the next_charge_scheduled_at property from the object obj, converts it into a date object, and then returns its .getTime() value.

findClosest(sampleData, acc) identifies an object in the given sampleData array that is closest to the current time (Date.now()). The .getTime() value of this element is stored in the constant closest, which is used to filter through the original input array once again:

const sampleData = [{
    "max_retries_reached": 0,
    "next_charge_scheduled_at": "2022-06-23T00:00:00",
  },
  {
    "max_retries_reached": 0,
    "next_charge_scheduled_at": "2022-06-23T00:00:00",
  },
  {
    "is_swappable": true,
    "max_retries_reached": 0,
    "next_charge_scheduled_at": "2022-06-23T00:00:00",
  },
  //Additional data entries...
];
const 
 findClosest = (data, accessor, target = Date.now()) =>
  data.reduce((prev, curr) => {
    const a = Math.abs(accessor(curr) - target);
    const b = Math.abs(accessor(prev) - target);
    return a - b < 0 ? curr : prev;
 }),
 acc=obj=>new Date(obj.next_charge_scheduled_at).getTime(),
 closest=acc(findClosest(sampleData,acc));
 
console.log(sampleData.filter(d=>acc(d)===closest));

An alternative version is provided below, which is more concise and eliminates the redundant calculation of Date objects:

function getClosest(arr){
  const trg = Date.now();
   times = sampleData.map((d, i) => [new Date(d.next_charge_scheduled_at).getTime(), i]),
   closest = times.reduce((p, c) => Math.abs(c[0] - trg) < Math.abs(p[0] - trg) ? c : p)[0];
  return times.reduce((a, [t, i]) => (t == closest && a.push(arr[i]), a), []);
}

getClosest() utilizes a temporary array named times to store the computed .getTime() value along with the index i for each object. After determining the closest time to Date.now(), the times array undergoes a reduce() operation to compile the results from the initial input array arr.

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

"Modify the MySQL database each time a user changes the value in a

As a student, I am looking to update value(s) whenever a student changes the value(s) in the correction or update form. So far, I have been able to retrieve and display values in text boxes based on the name selected from a dropdown list from the database ...

A PHP guide on iterating through statement results to populate an associative array

I am struggling to find the correct syntax to iterate through my results and populate them into an associative array. Currently, it only retrieves the first result and does not continue looping through the rest of the data. I have attempted various combina ...

There appears to be an issue with Mongoose Unique not functioning properly, as it is allowing

Below is the complete code snippet I am using to validate user data: import { Schema, model } from 'mongoose'; import { User } from './user.interface'; const userSchema = new Schema<User>({ id: { type: Number, required: ...

Issues with Jquery Checkboxes Functionality

Hi everyone, yesterday I had a question and since then I have made quite a few changes to my code. Right now, I am attempting to make some JavaScript work when a specific checkbox is checked. However, nothing is happening when I check the checkbox. Can any ...

Using a variable in a Joomla module to create a JavaScript object with PHP

I am currently developing a Joomla module that features a progress bar utilizing the ProgressBar.js plugin. Since this module is designed to load multiple objects on a single page, hardcoding the IDs of these objects is not feasible. To address this, I uti ...

Why Won't My PHP Form Submit on a Bootstrap Website?

I'm struggling with validation and need some assistance. I have a Bootstrap form embedded within an HTML page and a PHP script to handle the submission. However, whenever someone clicks on Submit, the page redirects to display my PHP code instead of a ...

JavaScript failing to render AJAX request

I have a website that utilizes AJAX to fetch data in JSON format from the backend and then displays it on the page. The website is built using MVC .NET framework. Below is the function responsible for loading events from the backend: function initEvents( ...

An unexpected issue occurred while converting XML data into JSON format

I have been using a piece of code that converts XML to JSON: // Converting XML to JSON var XmlToJson = function xmlToJson(xml) { //console.log('called xmltojson'); //console.log(xml); // Creating the return object var self = this ...

Angular.js page failing to reflect changes following Firebase request completion

myApp.controller('RegistrationController', ['$scope', function($scope) { var auth = firebase.database().ref(); // console.log("auth::"+auth); $scope.login = function() { $scope.message = "Welcome " + $scope.user.ema ...

Pug does not have access to computed properties within the dynamic class attribute of a Vue component

After attempting to dynamically toggle the className based on computed property and encountering issues in Pug, I found that manually setting 'true' to a className was the solution. Even after trying to reassign the computed property to a Pug var ...

Challenges when testing Angular controllers using Jasmine - modular problem

Recently, I made the decision to explore testing my Angular code using Jasmine. While everything seems to work fine without specific dependencies, I encountered problems when there are dependencies involved. For instance, in our project we use controllers. ...

Class for making elements draggable using jQuery UI

Is it possible to use jQueryui's draggable/droppable combo and add a class to the dragged item when dropped into a specific container, rather than adding a class to the container itself? I've tried adding a class to the container, but that is not ...

What is the best way to retrieve data from multi-dimensional JSON structures?

Looking to extract specific values from my JSON file. console.log( objects.assignments.header.report_type ); I need to display HOMEWORK Javascript $.ajax({ url: "/BIM/rest/report/assignment", type: "POST", dataTyp ...

Is it possible to link actions to a storage location external to a component?

Imagine having a store set up with a middleware called redux-thunk. The store is created and exported using the following code: import myOwnCreateStoreMethod from './redux/createStore'; export const store = myOwnCreateStoreMethod(); Now, you ha ...

Storing the selected radio button value in AsyncStorage using React Native: A step-by-step guide

Can anyone help me with storing the users selected radio button value in AsyncStorage? I have radio button values being retrieved from another file and assigned to labels. Here is an example of how my radio buttons are structured: import RadioButtonRN fr ...

Searching for various object values within an array and then adding two properties together in JavaScript

I am working with an array of objects that require me to analyze two properties in order to calculate a value. let data = [ { NodeId: "9837f279", NodeName: "Node1", summary: { current: 50, limit: 75 ...

Accessing Angular templates scope after the document is ready using angular.element()

I am currently learning Angular and experimenting with the Symfony2 + AngularJS combination. I am facing a specific issue that I need help with: Within my index.html file, I have the following script: <script> global = {}; $(document).ready ...

Troubleshooting a problem with jQuery: alter background color when checkbox is

I recently created a script to change the background color when a radio button is selected. While it works for checkboxes, I noticed that when another radio button is selected, the previous one still remains with the selected color. <script type="text/ ...

I am no longer able to connect to mySQL using node js

I recently upgraded my node version, and now I'm facing issues accessing my database through my application. I have tried various solutions such as: - Changing the route to 127.0.0.1. - Adding my port number 3306. - Including socketPath: '/Applic ...

Error encountered: Unexpected '<' token when trying to deploy

Trying to deploy a React app with React Router on a Node/Express server to Heroku, but encountering the following error... 'Uncaught SyntaxError: Unexpected token <' Suspecting the issue may lie in the 'catch all' route in the Expr ...