How can I choose all the items within an Array that fall within a specific DateTime range?

In order to explore the various methods of querying an array table similar to how MySQL works, I have devised this example.

Among the 8 queries presented below, the one that is challenging me is Query (6), which involves using Array.find() in a MySQL DateTime range SELECT.

const tblUsers = [{
    id: 101,
    user: 'user1',
    password: 'password1',
    created: '2021-01-01 00:00:01',
    modified: '2021-01-01 23:59:59',
    status: 'Active',
    firstName: 'Sean',
    lastName: 'Connery'
  },
  {
    id: 102,
    user: 'user2',
    password: 'password2',
    created: '2021-01-05 00:00:01',
    modified: '2021-01-05 23:59:59',
    status: 'Inactive',
    firstName: 'Bill',
    lastName: 'Murray'
  },
  {
    id: 103,
    user: 'user3',
    password: 'password3',
    created: '2021-01-10 00:00:01',
    modified: '2021-01-10 23:59:59',
    status: 'Active',
    firstName: 'Jeniffer',
    lastName: 'Connelly'
  },
];

let user4: any = {
  id: 104,
  user: 'user4',
  password: 'password4',
  created: '2021-01-15 00:00:01',
  modified: '2021-01-15 23:59:59',
  status: 'Active',
  firstName: 'Michelle',
  lastName: 'Pfeiffer'
};

// (0) - INSERT INTO tblUsers (id, user, password, ...) VALUES (104, 'user4', 'password4', ...);
tblUsers.push(user4);

// (1) - Select * FROM tblUsers;
let selectAlUsers: any = tblUsers || null;
console.log(tblUsers);

// (2) - Select * FROM tblUsers WHERE id = 103;
let selectUserById: any = tblUsers.find(record => record.id === 102) || null;
console.log(selectUserById);

// (3) - Select * FROM tblUsers WHERE firstName = 'Bill';
let selectUserByFirstName: any = tblUsers.find(record => record.firstName === 'Bill') || null;
console.log(selectUserByFirstName);

// (4) - Select * FROM tblUsers WHERE lastName = 'Murray';
let selectUserByLastName: any = tblUsers.find(record => record.lastName === 'Bill') || null;
console.log(selectUserByLastName);

// (5) - Select * FROM tblUsers WHERE status = 'Inactive';
let selectUsersByStatus: any = tblUsers.find(record => record.status === 'Inactive') || null;
console.log(selectUsersByStatus);

// (6) - Select * FROM tblUsers WHERE created BETWEEN '2021-01-05 00:00:01' AND '2021-01-10 00:00:01';
// let userRecordsByDateTimeRange: any = tblUsers.find(record => record.created === '2021-01-05 00:00:01' && record.created === '2021-01-10 23:59:59');
// console.log(userRecordsByDateTimeRange);

// (7) - UPDATE tblUsers SET modified = '2021-01-06 00:00:00', status = 'Active', ... WHERE id = 102;
function updateUserById(): boolean {

    let selectUserById: any = tblUsers.find(record => record.id === 102) || null;

    if(!selectUserById) return false;

    let user2: any = {
      // id: 102,
      // user: 'user2',
      // password: 'password2',
      // created: '2021-01-15 00:00:01',
      // modified: '2021-01-15 23:59:59',
      status: 'Active',
      // firstName: 'Bill',
      // lastName: 'Murray'
    };

    // Execute Update

    // selectUserById.user      = String(user2.user);
    // selectUserById.password  = String(user2.password);
    // selectUserById.created   = String(user2.created);
    // selectUserById.modified  = String(user2.modified);
    selectUserById.status    = String(user2.status);
    // selectUserById.firstName = String(user2.firstName);
    // selectUserById.lastName  = String(user2.lastName);
    return true;
}
console.log(updateUserById());

// (8) - DELETE FROM tblUsers WHERE id = 102;
function deleteUserById(): boolean {

    let selectUserById: any = tblUsers.find(record => record.id === 102) || null;
    let userArrayIndex: any = tblUsers.findIndex(record => record.id === 102) || null;

    if(!selectUserById) return false;
    if(!userArrayIndex) return false;

    // Execute Delete
    tblUsers.splice(userArrayIndex, 1); // remove 1 element at userArrayIndex

    return true;
}
console.log(deleteUserById());

Answer №1

If you want to convert timestamps to epoch, you can utilize the new Date() method and then compare the epochs. Additionally, you can make use of Array.filter() to retrieve multiple records.

let userRecordsByDateTimeRange: any = tblUsers.filter(
    record => new Date(record.created).getTime() >= new Date('2021-01-05 00:00:01').getTime() 
    && new Date(record.created).getTime() <= new Date('2021-01-10 23:59:59').getTime()
);
console.log(userRecordsByDateTimeRange);

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

A function that can handle either a generic data type or an array containing elements of the same data type

function process<Type>(input: Type | Type[]): Type { if (Array.isArray(input)) { // input here is definitely Type[] return input.map((element) => process(element) /* <- this error message is saying 'Type[]' is not the ...

Utilize Electron's fs to stream a file directly to an HTML video player while it is being downloaded

I am currently exploring the possibility of using the HTML video player to stream a file from the file system within Electron. My goal is to initiate streaming while the file is still being downloaded. I am uncertain whether my current approach will be ...

Tips for regularly retrieving information from a psql table

I have a scenario where I am retrieving data from a psql table and converting it into a JSON array to be used for displaying a time series chart using JavaScript. The data that is passed needs to be in the form of an array. Since the data in the table get ...

Accessing a key from an object dynamically in a React list and resolving key error issues in React

I encountered two challenges: I am currently retrieving JSON data from APIs. [ { "title": "Basic Structures & Algoritums", "lesson_id": 3, "topics": { "Title": &q ...

"Learn the trick to concealing a modal and unveiling a different one with the power of jquery

Whenever I try to open a modal, then click on a div within the modal in order to close it and open another one, I encounter an issue. The problem is that upon closing the first modal and attempting to display the second one, only the background of the seco ...

Is there a way to link Dom $(this) from a different function?

Could you please review this code and advise on how I can bind $(this) in an external function within a DOM event? $(".adder").on("click", function(){ updateText(); }); function updateText(){ $(this).next(".mapper").html("Got You!"); } <scrip ...

What are the steps to integrate TypeScript into JavaScript code?

How can I import a TypeScript class in a Node CommonJS JavaScript file? When using mongoose in my TypeScript code, I typically do the following: // user.model.ts export const UserModel = model<User>('User', schema); In my JavaScript code: ...

The VSCode's intellisense for Angular Material fails to function effectively

In the midst of my project on Angular version 13, I have successfully installed Angular Material using the command below: ng add @angular/material The package has been properly included in the node_modules folder. However, when working with TypeScript ...

The Angular 2 application functions perfectly when running locally, but encounters issues when running on an ec2 instance

When trying to upload an Angular 2 application to an AWS EC2 t2.small instance, it is not working as expected, even though it runs successfully in a local server. Node version: v7.0.0 NPM version: 3.10.8 There has been an EXCEPTION: Uncaught (in prom ...

In the realm of JavaScript, what happens when a function yields yet another function while also welcoming another function as an argument?

After following a Node & Express project tutorial on YouTube, I encountered the following code snippet in an async JavaScript file: const asyncHWrapper = (fn) => { return async (req, res, next) => { try { await fn(req, res, next); } c ...

Modify the background color of React-select when it is in a disabled state

I found this interesting tip on color customization in React Select When the select field is disabled, I want to change its color to something different. isDisabled={true} To achieve this, I am modifying the code as follows: > import React from &q ...

Improving the utilization of variables in HTML

I was looking for a way to create dynamic user detail forms using a template. Each element needed to have a unique id for proper posting of details. This is what my template looks like: <div id="user-template" class="hidden"> <div class=&apos ...

Material UI autocomplete bug: a frustrating issue with suggestions

I'm currently developing a single-page application using React, and I have a shipment page where multiple products and their quantities need to be added. I've implemented some functions for this scenario, and while they are working correctly (sen ...

What is the best way to make a POST request and pass two parameters when calling an API in Ionic?

Struggling to implement API calls in Ionic for the purpose of signing in. Unsure of the correct method to make the call. Previous attempts to call the API have been unsuccessful. signin.ts import { Component } from '@angular/core'; import { Na ...

What is the best way to sequentially invoke an asynchronous function within an Observable method?

Presently, I have the following method: public classMethod( payload: Payload, ): Observable<Result> { const { targetProp } = payload; let target; return this.secondClass.secondClassMethod({ targetProp }).pipe( delayWhen(() ...

VS code is showing the directory listing instead of serving the HTML file

Recently, I attempted to use nodejs to serve the Disp.html file by following a code snippet from a tutorial I found on YouTube. const http = require("http"); const fs = require("fs"); const fileContent = fs.readFileSync("Disp.html& ...

Using Express, Node, and Angular to transmit audio files to the frontend

I am currently working on serving audio files from a Node/Express backend to an Angular frontend. On the server side, the code looks like this: var file = "/filepath.wav"; res.download(file, 'testAudio.wav'); And here's the client side c ...

Steer clear of initializing arrays in Java

Can the need for array zeroing/initialization in Java be avoided? I have a requirement to rapidly create new byte arrays of a specific length that will be filled with predetermined data. This means I do not need the JVM to automatically zero out the array ...

Utilizing nested arrays to implement v-for loop for efficient data rendering

Within my array - 'items', each object contains another array of objects. I am trying to retrieve the second array called 'productPrices' in order to use v-for. However, items.productPrices is not working for me. Do I need to implement ...

Transform an Axios promise into a standard JSON array

I'm encountering some difficulties with a function that is supposed to return data. The function is intended to return JSON data, but instead, it is returning a promise. Below is the code for the function: import axios from 'axios'; cons ...