How can I organize an array in JavaScript by date for presentation on a webpage?

Check out this code snippet:

list.component.ts

const data1 = [
      {
        dateStart: "2020-02-14 00:00:01",
        name: 'Server1'
      },
      {
        dateStart: "2020-02-13 14:00:01",
        name: 'Server1'
      },
      {
        dateStart: "2020-02-13 13:00:01",
        name: 'Server1'
      },
      {
        dateStart: "2020-02-13 12:00:01",
        name: 'Server1'
      },
      {
        dateStart: "2020-02-13 11:00:01",
        name: 'Server1'
      }
    ];

    const data2 = [
      {
        dateStart: "2020-02-13 14:00:01",
        name: 'Server2'
      },
      {
        dateStart: "2020-02-13 13:00:01",
        name: 'Server2'
      },
      {
        dateStart: "2020-02-13 12:00:01",
        name: 'Server2'
      },
      {
        dateStart: "2020-02-13 11:00:01",
        name: 'Server2'
      },
      {
        dateStart: "2020-02-12 11:00:01",
        name: 'Server2'
      },
      {
        dateStart: "2020-02-11 11:00:01",
        name: 'Server2'
      },
    ]

    const arr = new Array();

    arr.push(data1, data2);


    arr.forEach(server => {
      const rec = orderBy(server, ['dateStart'], ['desc']);

  console.log(rec);
    });
  }

The aim is to only display the most recent entries from both data sets. Any duplicate dates should be eliminated in favor of older data.

Desired output:

[
  {
    dateStart: "2020-02-14 00:00:01",
    name: "Server1"
  },
  {
    dateStart: "2020-02-13 14:00:01",
    name: "Server1"
  },
  {
    dateStart: "2020-02-13 13:00:01",
    name: "Server1"
  },
  {
    dateStart: "2020-02-13 12:00:01",
    name: "Server1"
  },
  {
    dateStart: "2020-02-13 11:00:01",
    name: "Server1"
  }
],
[
  {
    dateStart: "2020-02-13 14:00:01",
    name: 'Server2'
  },
  {
    dateStart: "2020-02-13 13:00:01",
    name: 'Server2'
  },
  {
    dateStart: "2020-02-13 12:00:01",
    name: 'Server2'
  },
  {
    dateStart: "2020-02-13 11:00:01",
    name: 'Server2'
  }
]

View the code snippet here: https://stackblitz.com/edit/angular-akhhbp

If a new array (data3) is introduced with more data, it will undergo similar comparison and filtering as data1 and data2.

Example scenario:

data1 = [{
        dateStart: "2020-02-13 14:00:01",
        name: 'Server1'
      },
      {
        dateStart: "2020-02-13 13:00:01",
        name: 'Server1'
      },
      {
        dateStart: "2020-02-13 12:00:01",
        name: 'Server1'
      }]
    data2 = [ {
        dateStart: "2020-02-13 14:00:01",
        name: 'Server2'
      },
      {
        dateStart: "2020-02-13 13:00:01",
        name: 'Server2'
      },
      {
        dateStart: "2020-02-13 12:00:01",
        name: 'Server2'
      },
      {
        dateStart: "2020-02-13 11:00:01",
        name: 'Server2'
      },
      {
        dateStart: "2020-02-12 11:00:01",
        name: 'Server2'
      }],
    data3 = [ {
        dateStart: "2020-02-13 14:00:01",
        name: 'Server3'
      },
      {
        dateStart: "2020-02-13 13:12:01",
        name: 'Server3'
      },
      {
        dateStart: "2020-02-13 12:00:01",
        name: 'Server3'
      },
      {
        dateStart: "2020-02-13 11:00:01",
        name: 'Server3'
      },
      {
        dateStart: "2020-02-12 10:00:01",
        name: 'Server3'
      }]

Expected outcome:

[{
            dateStart: "2020-02-13 14:00:01",
            name: 'Server1'
          },
          {
            dateStart: "2020-02-13 13:00:01",
            name: 'Server1'
          },
          {
            dateStart: "2020-02-13 12:00:01",
            name: 'Server1'
          }],
 [ {
            dateStart: "2020-02-13 14:00:01",
            name: 'Server2'
          },
          {
            dateStart: "2020-02-13 13:00:01",
            name: 'Server2'
          },
          {
            dateStart: "2020-02-13 12:00:01",
            name: 'Server2'
          }],
[ {
            dateStart: "2020-02-13 14:00:01",
            name: 'Server3'
          },
          {
            dateStart: "2020-02-13 13:12:01",
            name: 'Server3'
          },
          {
            dateStart: "2020-02-13 12:00:01",
            name: 'Server3'
          },
          {
            dateStart: "2020-02-13 11:00:01",
            name: 'Server3'
          },
          {
            dateStart: "2020-02-12 10:00:01",
            name: 'Server3'
          }]

Answer №1

Here is my approach to solving the problem:

  • To begin, ensure that the arrays are sorted in descending order if they are not already. You can achieve this by using the array.sort() method.
  • Next, create a new array and copy the first array, denoted as data1, into it. Remember to store the last entry of this array in a temporary variable:
    let temp = data1[data1.length - 1].dateStart
    . This step ensures that you only consider data entries that are newer than this date during the merging process.
  • Proceed to iterate through the remaining arrays, such as data2, data3, ..., and add any data entries to the new array if their dateStart values are not older than the stored value in temp.

Answer №2

If you wish to preserve your data in a similar format, simply utilize the spread operator (...) as shown below:

const data1 = [
      {
        dateStart: "2020-02-14 00:00:01",
        name: 'Server1'
      },
      {
        dateStart: "2020-02-13 14:00:01",
        name: 'Server1'
      },
      {
        dateStart: "2020-02-13 13:00:01",
        name: 'Server1'
      },
      {
        dateStart: "2020-02-13 12:00:01",
        name: 'Server1'
      },
      {
        dateStart: "2020-02-13 11:00:01",
        name: 'Server1'
      }
    ];

    const data2 = [
      {
        dateStart: "2020-02-13 14:00:01",
        name: 'Server2'
      },
      {
        dateStart: "2020-02-13 13:00:01",
        name: 'Server2'
      },
      {
        dateStart: "2020-02-13 12:00:01",
        name: 'Server2'
      },
      {
        dateStart: "2020-02-13 11:00:01",
        name: 'Server2'
      },
      {
        dateStart: "2020-02-12 11:00:01",
        name: 'Server2'
      },
      {
        dateStart: "2020-02-11 11:00:01",
        name: 'Server2'
      },
    ]

let final = [[...data1], [...data2], ...more arrays];

The resulting output will be:

[ [ { dateStart: '2020-02-14 00:00:01', name: 'Server1' },
    { dateStart: '2020-02-13 14:00:01', name: 'Server1' },
    { dateStart: '2020-02-13 13:00:01', name: 'Server1' },
    { dateStart: '2020-02-13 12:00:01', name: 'Server1' },
    { dateStart: '2020-02-13 11:00:01', name: 'Server1' } ],
  [ { dateStart: '2020-02-13 14:00:01', name: 'Server2' },
    { dateStart: '2020-02-13 13:00:01', name: 'Server2' },
    { dateStart: '2020-02-13 12:00:01', name: 'Server2' },
    { dateStart: '2020-02-13 11:00:01', name: 'Server2' },
    { dateStart: '2020-02-12 11:00:01', name: 'Server2' },
    { dateStart: '2020-02-11 11:00:01', name: 'Server2' } ] ]

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

The property 'licenses' has incompatible types. The type 'License[]' cannot be assigned to type 'undefined' in the getServerSideProps function while using iron-session

I am encountering an issue with red squiggly lines appearing on the async keyword in my code: Argument of type '({ req, res }: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>) => Promise<{ props: { admin: Admin; licenses?: undefined ...

Access a file from an npm module using an executable command

I have a npm module called @jcubic/lips, which includes an executable file. I need to open a file located within the module's directory. This module is installed globally. The specific file I want to access is ../examples/helpers.lips, relative to th ...

Angular 2 Validation Customizer

Recently, I created a web API function that takes a username input from a text field and checks if it is already taken. The server response returns Y if the username is available and N if it's not. For validating the username, I implemented a Validat ...

jQuery UI Sortable: Efficiently Drag Items Across Multiple Interconnected Lists

One feature of using jQuery UI Sortable is the ability to make the sortable item container scroll when an item is dragged. This can be achieved by specifying the scroll option. In my case, I have several sortable lists that are connected within separate c ...

Troubleshooting: Difficulty with Angular 2 TypeScript interface array functionality

Currently, I am developing an Angular 2 application where I aim to showcase messages by utilizing an interface and storing all the messages in an array. Below is a snippet of my TypeScript component that highlights this functionality: export class ChatCom ...

Tips for effectively transferring data between components in Angular 2

One of the challenges I'm facing is with my header component. It has a function that toggles a class on click, and it works perfectly within the header component. However, I now want to extend this functionality to my nav component in order to add cla ...

Incorrect Reactjs installation technique

When I try to run create-react-app on my Windows PC, only dependencies are being installed with no folders other than node_modules. Even when using Yarn, I haven't been able to progress further. Please assist and thank you in advance for any help. Thi ...

Cyber Platform

I recently encountered a challenge while working on my web project. What are some areas that can be improved? import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import {map} from 'rxjs/op ...

Shifting hues with every upward and downward movement

I am experiencing a small issue with this JS code... -I have multiple divs that are changing automatically in rows as they move randomly... I want to change the color of the div moving up to green. And for the div moving down, I want to change the colo ...

A specialized HTTP interceptor designed for individual APIs

Hey there, I am currently working with 3 different APIs that require unique auth tokens for authentication. My goal is to set up 3 separate HTTP interceptors, one for each API. While I'm familiar with creating a generic httpInterceptor for the entire ...

Unable to access filteredItems from custom popup in uib-typeahead retrieval process

Issue with Retrieving Filtered Items from ng-repeat in Controller using $scope Despite trying to fetch filtered items from ng-repeat, the value of $scope.filteredItems appears as undefined when I log it to the console. I attempted to implement the solutio ...

Using TypeScript in conjunction with Node.js

I'm currently trying to use typescript with nodejs, but I keep encountering errors. Can anyone help me troubleshoot? Here is the code snippet (assuming all necessary modules are imported): import routes from "./routes/routes"; let app = express(); ap ...

Performing an AJAX call with JQuery when clicking on multiple anchor elements

I have a set of anchor tags created dynamically through PHP from a database query, like the following: <a href="#" id="reply_doc" data-doc_value="1"></a> <a href="#" id="reply_doc" data-doc_value="2"></a> <a href="#" id="reply_d ...

Behind the scenes, unable to launch due to Schema Error

My experience with Backstage was going smoothly until I ran into an issue after executing a yarn install this afternoon. Now, whenever I attempt to run yarn dev, it fails with the following error: [0] Loaded config from app-config.yaml [0] <i> [webpa ...

Issue encountered: Document not being saved by Mongoose, error message received: "MongoClient connection must be established"

Currently, I am attempting to establish a connection with MongoDb using mongoose. Below is the code snippet that I have implemented for this purpose: controller.js const conn = mongoose.createConnection(db, { useNewUrlParser: true, ...

Incorrect posture during the movements

Utilizing Jquery Drag and Drop, I have implemented two swap-able divs. However, during the animation process of swapping the divs, their positions are not properly maintained. The actual swapping of the divs works correctly, but there is an issue with the ...

How to display an array with JSON objects in Angular 4

Looking to display specific data from an array in my .html file that originates from my .ts file: myArray: ["03/05/2018", "2:54", "xoxo", "briefing", "your", [{ "Id": "1", "Time": "20:54", "Topic": "mmmmm", "GUEST1": { "Role": "HS" ...

Challenge with React CloneElement regarding typing

Utilizing React Children and React Clone element, I aim to trigger methods in both the wrapper and Select components upon onClick event in the Option component. Although everything is functioning correctly, I am encountering a type error when calling the O ...

Leverage D3 force simulation as a functional programming tool

Currently, I am utilizing d3-force for collision detection in my project: function customLayout(nodesWithCoordinates) { const simulation = forceSimulation(nodesWithCoordinates) .force('collide', forceCollide(4.5)) .stop() .tick(300 ...

After clicking a button in AngularJS, how can you retrieve one of the two JSON files and store it in a $scope variable?

For instance, You have two JSON files: Json file #1: [{colorname:blue},{colorname:blue}] Json file #2: [{colorname:red},{colorname:red}] Within the controller, there exists a variable called $scope.color In the HTML code, there are two buttons named " ...