What are the best ways to utilize moment and lodash for grouping objects based on fields and counting by dates?

I'm facing a rather complex scenario where I'm looking for a way to manipulate data using lodash and moment. Let's say I have a date range and the following initial data:

var startDate = "2018-02-21"
var endDate = "2018-02-23"
var data = [
      {
       "date": "2018-02-21 21:21:17",
       "group": "A"
       },
      {
       "date": "2018-02-21 21:21:17",
       "group": "B"
       },
      {
       "date": "2018-02-23 21:21:17",
       "group": "A"
       },
      {
       "date": "2018-02-21 21:21:17",
       "group": "B"
       }
  ];

My goal is to utilize lodash to group all the "group" fields and create a new field in the resulting object called "dates". This new field will consist of key/value pairs representing dates, where the keys will be within the date range (from startDate to endDate) and the values will indicate the count of matching dates.

The desired output format would be as follows:

 var output = [
    {
        "group": "A",
        "dates": [
            "2018-02-21": 1,
            "2018-02-22": 0
            "2018-02-23": 1
        ]
    },
    {
        "group": "B",
        "dates": [
            "2018-02-21": 2,
            "2018-02-22": 0,
            "2018-02-23": 0
        ]
    }
  ];

I have set up a jsfiddle with moment and lodash included to illustrate this scenario.

http://jsfiddle.net/dp7rzmw5/6467/

Your assistance with this matter would be greatly appreciated!

Answer №1

If you're looking to tackle this issue using pure JavaScript, here's a step-by-step guide on how to do it:

Step 1: Start by creating an array of dates within the specified range. This array will come in handy if there are any missing dates in your data set.

var dates = [];
var startDate = new Date("2018-02-21");
var endDate = new Date("2018-02-23");
for (var s = startDate; s <= endDate; s.setDate(s.getDate() + 1)) {
    dates.push(s.toISOString().split('T')[0]);
}

Your dates array will now look like this:

[ "2018-02-21", "2018-02-22", "2018-02-23" ]
.

Step 2: Utilize the .reduce() method on your data to aggregate the desired values. Combine this with .forEach() on the dates array to fill in any missing days in case there is no data available.

var groups = [];
var output = data.reduce((obj, item) => {
    var d = new Date(item.date).toISOString().split('T')[0];
    var x = groups.indexOf(item.group);
    if (x === -1) {
        groups.push(item.group);
        x = groups.indexOf(item.group);
    }
    obj[x] = obj[x] || {};
    obj[x]["date"] = obj[x]["date"] || {};
    dates.forEach(date => {
        if (!obj[x]["date"][date]) {
            obj[x]["date"][date] = 0;
        }
    });
    obj[x]["date"][d]++;
    obj[x]["group"] = item.group;
    return obj;
}, {});

The final output will look like this:

{
  "0": {
    "date": {
      "2018-02-21": 1,
      "2018-02-22": 0,
      "2018-02-23": 1
    },
    "group": "A"
  },
  "1": {
    "date": {
      "2018-02-21": 2,
      "2018-02-22": 0,
      "2018-02-23": 0
    },
    "group": "B"
  }
}

Copy and paste the provided code into your web console to visualize the result using console.table(output).

I've also made some adjustments to your jsfiddle demo for better demonstration.

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

Encountering a Keyerror while attempting to access a specific element within a JSON data

I have come across this question multiple times, but the JSON I need to access seems to be slightly different. The JSON structure looks like this: { "timestamp": 1589135576, "level": 20, "gender": "Male", "status": {}, "personalstats": {}, "at ...

Error message encountered in PHP due to an undefined index

My goal is to add items from a form to a table named products. The form layout can be seen here: https://i.stack.imgur.com/f9e08.png The "Add more suppliers: +" link adds a new row to the form when clicked. The corresponding script for this action is as ...

Tacking the progress bar onto an array of $.ajax() calls within a Promise.all

FINAL UPDATE 25/06/20: After a thorough investigation, I discovered the root causes of why the progress bar was not functioning as intended. Firstly, dealing with $.ajax() proved to be cumbersome due to its lack of proper promise handling. To resolve this ...

Verify if the React component is empty

Within my react component, there's a class or component that contains a specific variable. Below is the relevant code snippet: import React from 'react'; export class Header extends React.Component { constructor() { super(); thi ...

generate a list based on the data inside an array of objects

How can I extract the values from the 'urban' field of type 'gasolina'? { ... "fuelUse" : { "urban" : [ { "value" : 6.2, "unit" : "km/l&qu ...

Axios has encountered a status code 429 and the request has failed

I've been encountering a recurring issue while trying to extract and save a large amount of data from an external API endpoint to my Database. The error code 429 keeps popping up. Despite attempting to use timeout and sleep libraries, I haven't ...

Turn off Appbar padding at the top and bottom

I am looking to create a customized box within the Appbar that spans the full height, as illustrated in the image below: https://i.stack.imgur.com/CFMo0.jpg However, the default Appbar provides padding from all sides to its internal elements, leading to ...

Issues detected between Angular and Express rendering operations

Having an issue with my angular code. It runs perfectly on its own, but when I try to access it on localhost with express, it only displays the HTML file. Here's my server code: var express = require('express'), app = express(); app ...

Error message: validator is not defined when integrating jquery.validate with jquery.uploadfile package

Currently, I am facing an issue while attempting to incorporate both jquery.validate and jquery.uploadfile on the same page. The error message I'm receiving is: TypeError: validator is undefined if ( validator.settings.rules ) { Interestingly, if ...

Creating a custom progress bar using Javascript and Jquery

I developed a progress bar that is fully functional. Here is the HTML structure: <div class="progress"> <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style ...

Having trouble identifying whether a file is a picture or video based solely on its extension

My current challenge involves determining whether an uploaded file is a video or a photo. This distinction is crucial as it dictates whether the file should be sent to my telegram bot as a video or photo attachment. Despite having what seems like a logica ...

The D3.extent() function is raising a TypeError because it is unable to iterate over the

I have been struggling with this issue for the past few hours, and I could really use some help. I'm not very familiar with using D3 in conjunction with React. Essentially, I have an anomaly detection algorithm running on the backend Flask App that r ...

When using `console.log`, the object is displayed correctly. However, an error occurs when

Here is the code I've been working on: function parseJSONData(jsonData){ var property, type, name, identifier, comment, content; for(property in jsonData){ switch(property){ case "type": type = jsonData[ ...

What is the correct way to log a complex object using Serilog so that it is formatted in valid

Presented is the structure below: public class LogRequestParameters { public string RequestID { get; set; } public string Type { get; set; } public string Level { get; set; } public string DateTime { get; set; } public string Machi ...

Tips for displaying a div briefly before loading the second page

Incorporating a div named ADD, I aim to successfully load a second page within the current one using ajaxload. The challenge lies in displaying a div for 4 seconds before loading the second page. How can this be achieved? Following the wait period, the sec ...

Validation of the hidden subcategory field using jQuery is essential

I am struggling with implementing jQuery validation on a form that includes fields for title, category, subcategory, and message. While I have successfully added validation for all fields except subcategory, it just won't seem to work. I could really ...

Experiencing issues with utilizing long polling on a node.js server URL in Internet Explorer

Currently, I am in the process of testing an application that utilizes long polling with jQuery to query a server built with node.js. The code for long polling is as follows: (function poll(){ $.ajax({ url: "http://localhost:3000/test", ...

The proxy feature in create-react-app does not function properly

When setting up my React app using create-react-app, I included the following in my package.json: After setting "proxy":"http://localhost:3001" in the package.json file to point to my API server running on port 3001, I encountered an issue where requests ...

Visualization of extensive datasets in JavaScript

I'm currently developing a dashboard in JS for displaying sales data plots to users. Can anyone recommend a JavaScript library that meets the following criteria: Capable of plotting a large number of points (ex: 100k or more) Interactive functional ...

Tips for inserting multiple JSON data links into Mysql

How can I efficiently extract JSON data from multiple links and save it into a MySQL database? Is there a way to modify the code below to enable reading from several URLs? <?php //connect to mysql db $con = mysql_connect("username","password", ...