Populate an array with missing dates by including the day and a count of zero using Javascript

I'm currently using a code to analyze daily occurrences over the past 7 days. However, the code only captures days with occurrences and skips those without any data. I want to include all days in the analysis, even if they have a count of 0. Here's my current code:

var myObj;
fetch('https://blahblahblah?'+param1+param2+"FromDate"+"="+moment().subtract(7,'d').format('YYYY-MM-DD'))
.then(res=>res.json())
.then(data=>myObj= data);

var myRes= [];

myObj.forEach(function (elem) {
    var date = elem.CreatedDate.split(' ')[0];


    if (myRes[date]) {
        myRes[date] += 1;
    } else {
        myRes[date] = 1;
    }
});

The current output looks like this:

2020-12-11: 1
2020-12-12: 2
2020-12-13: 1
2020-12-15: 2
2020-12-16: 1

However, I would like the output to include days with 0 values, as shown below:

2020-12-10: 0
2020-12-11: 1
2020-12-12: 2
2020-12-13: 1
2020-12-14: 0
2020-12-15: 2
2020-12-16: 1

Your help will be greatly appreciated.

Edit: Here is a sample object data:

[{Id, Var1, Var2, CreationDate},
{1, 123, Var2, 2020-12-11},
{2, 1234, Var2, 2020-12-12},
{3, 12345, Var2, 2020-12-12},
{4, 1234, Var2, 2020-12-13},
{5, 321, Var2, 2020-12-15},
{6, 3214, Var2, 2020-12-15},
{7, 5432, Var2, 2020-12-16}]

Answer №1

After computing myRes, you can generate an array containing the dates of the last 7 days and then compare it with myRes to construct finalResult that includes any missing dates.

let myRes = {
    '2020-12-11': 1,
    '2020-12-12': 2,
    '2020-12-13': 1,
    '2020-12-15': 2,
    '2020-12-16': 1,
}


const dates = [];
const NUM_OF_DAYS = 7; // retrieve last 7 dates.

for (let i = 0; i < NUM_OF_DAYS; i++) {
  let date = moment();
  date.subtract(i, 'day');
  dates.push(date.format('YYYY-MM-DD'));
}


let finalResult = {};
dates.reverse().forEach(date => {
    if(!myRes.hasOwnProperty(date)) {
        finalResult[date] = 0;
    } else {
        finalResult[date] = myRes[date];
    }
});

console.log(finalResult);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Answer №2

Are you satisfied with this modification?

let newArray = Array(5).fill(null);

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

How can I cut an array by value in Vue?

I am working on a component that has a list of objects and I need to implement functionality where, when toggled, the objects' title prop is either added to or removed from an array. Adding the value was easy to do, but removing it has proven challeng ...

Tips for rearranging the order of x-editable events?

I'm currently developing a web application using angularJs and xeditables. Within this application, I have multiple xeditable text elements following each other, with validation triggering upon pressing enter or clicking outside the text field: &l ...

Managing and comparing category IDs in JavaScript to effectively store and render subcategories

My goal is to set the current category ID in a variable, and if the category changes, I want to store that as well. Then, I need to compare both IDs. If they are not equal, I want to set the subcategory to null. However, I am unsure of where my mistake lie ...

What steps can I take to ensure that this input is neat and tidy

I need to implement conditional styling for my input field. The current layout is chaotic and I want to improve it. Specifically, when the active item is "Height", I only want to display the height value and be able to change it using setHeight. const [a ...

The onKeyUp event is not functioning as expected in React, unlike the onChange event

For a React coding challenge, I am required to update a value onKeyUp instead of onChange. However, after changing it to onKeyUp, my fields are not updating and I cannot type anything into the textarea. class MarkdownApp extends React.Component { constr ...

Multiplication of matrices in C programming is done in two dimensions

I have written a code in C language for matrix multiplication. However, I'm facing an issue where the desired output is not being produced. I'm unsure of which part of my code might be incorrect or if I missed something crucial. https://i.sstati ...

Encountered an issue while attempting to append to my Leaflet map's LayerGroup

I've encountered an issue while trying to integrate LayerGroup into my map in order to enable Leaflet Control Search for city-based searches. The problem seems to be related to an undefined return value or something similar. Since I'm relatively ...

Order of execution in Single Page Applications when using multiple files: understanding the Javascript async defer concept

I am currently working on enhancing the performance of my webpage, which is built using EmberJS. One strategy I'm considering is utilizing `asyc` and `defer` attributes for our Javascript files. I have already implemented other optimizations such as ...

Is it possible to resize without defining dimensions?

Currently, I am working with Access 2010 on Win7. I have recently discovered that I can dynamically size my arrays at runtime simply by using ReDim arrayName(x) without having to declare the array with Dim arrayName() first. Sub FooBar() ReDim myArray( ...

Unauthorized access for POST request in WooCommerce API: 401 error

Let's start by examining the complete code to better understand the issue at hand. Here is the WooCommerce API authentication using the consumer key and secret from the file checkout.ts: this.WooCommerce = WC({ url:"http://localhost/ ...

Calculating the required force vector to score a basketball shot using Ammo.js and Three.js

Currently in the process of developing a basketball game using three.js and ammo.js. The positions of the hoop/rim and ball are constantly changing, making the shots dynamic and relative. I am tasked with determining the correct force vector needed for a ...

Convert an array to a string in ES6 without using commas

Is there a way to transform a list of errors into a tooltip-friendly format without adding commas between each item? The list is being displayed with an unwanted comma after every li element. I suspect this issue arises from the use of errors.map(error =& ...

Encountering difficulties linking to a stylesheet or a script in an HTML file delivered by Express server

Currently, I'm facing the challenge of breaking down my Express app code into multiple files. Unfortunately, I am unable to utilize <link href> or <script src> for linking stylesheets or scripts. Below is the relevant snippet from my inde ...

Unable to use npm module "csv-db" as it is currently experiencing functionality issues

Looking to implement a "lightweight offline database" that stores data in .csv files. The module I am using can be found in the documentation: https://www.npmjs.com/package/csv-db Unfortunately, I've been encountering issues with this module and have ...

What is the best way to execute a task in Grunt when supplied with a dynamically-generated array of filenames?

Although I am relatively new to using Grunt, I have developed a good understanding of how tasks are installed and executed. Currently, I am successfully running tasks such as minifying js, copying files, and executing jshint. Now, my goal is to implement ...

adding to array in vb.net 2008

There is a message that variable j is being used before it has been assigned a value. This issue may not be a problem in PHP language. Dim j() As String Dim i As Integer If (i = 1) Then j(0) = "x" Else j(0 ...

On top of the world always is Mesh or Sean

Currently I am working on a 3D diagram, possibly using a bar or line graph. I have been using three.js version 60 as most of my code has already been developed with this version. However, I am facing an issue with adding legends to the diagram. The 3D obje ...

When the parent component in React JS rerenders, the props are not automatically passed down to the child

I have come across similar questions in the past, but I have not found any answers that directly address the issue I am facing in my scenario. In my case, there is a parent component that passes a property to a child component's state. Depending on t ...

The program encounters an error when attempting to use strcpy() to set values in a struct, causing it

I'm a beginner in the world of C programming and I've encountered a challenge while trying to assign values to a struct using strcpy. Despite attempting the lvalue method for assignment, an error is thrown. When I run the program, no output is ge ...

What is the best way to remove the excess numbers from the return date provided by the react-date-picker?

I need help displaying only the Month and Day with the format "Tue Oct 22 2019". Currently, I am getting "Tue Oct 22 2019 00:00:00 GMT-0700 (Mountain Standard Time)" when using "react-date-picker". How can I achieve this without having to truncate the te ...