What is the best way to populate an array with zeros when there is no data available?

Currently, I am working on a project that involves using chart.js to display monthly profit data up to the current month. The data is retrieved from the server and there are two scenarios to consider:


        // First scenario
        data: [
            {month: 1, profit: 23},
            {month: 2, profit: 678},
            .
            .
            {month: 9, profit: 456}
        ]
    

In this first scenario, I need to complete the data set up to 12 months with zero profit for the missing months.

Second scenario


        // Second scenario
        data: [{0: {month: 9, profit: 23}}]
    

In this second scenario, I need to fill the array from month 1 to 12 with zero profit, excluding month 9 (September). How can I achieve this?

Answer №1

Feel free to experiment with this Plunker. It can serve as a starting point for you, allowing you to customize and adapt it according to your specific requirements.

 while (i < 12){
    if(data[prev] && i == data[prev][prev].month) {
      array.push(data[prev][prev]);
      prev++;
    } else {
      array.push({i:{month: i, profit: 0}});
  }
i++;

}

So this will essentially be the core of your function. All you need to do is adjust the final array to align with the chart.js format. Hopefully, this information proves valuable to you.

Answer №2

Take a look at this awesome fiddle

In essence, ensure your data is clean. Iterate through your data and store it in an array. Then iterate through a 12-month array and insert 0 where there are missing values.

data.forEach(function (item) {
  // -> loop through all keys in the item
  //    -> for each key, extract the month and profit and add to result
  //    -> result[month] = profit
});

Time to fill the gaps

// create a blank array with 12 slots
Array.apply(null, {length: 12 }).forEach(function (i, month) {
  // -> if result[month] == null
  //    -> this means there is no data for that month.
  //    -> add it to the result with profit 0
  //    -> result[month] == 0
});

Utilize the result array in your chart.

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

Inconsistent reliability of Loopback-context prompts the search for an alternative solution

After encountering some reliability issues with the loopback-context package, I decided to try an alternative approach. Instead of relying on setting the current user object in my middleware using loopback-context, I opted to fetch the accessToken from the ...

Unresolved promise within a nested service in the then() method

I am facing an issue with a particular service that requires retrieving an access token followed by a User object. Once this process is complete, further UI actions need to be executed. The problem lies in the fact that the login().then() function is being ...

Embed the Nest API into your HTML5 code

My mobile HTML5 application includes a script in the index.html file. Nest.js (code below) Whenever I run my application, I encounter an error stating that Firebase is not defined. This is odd because the function seems simple: --> var dataRef = new ...

Issue with PLUploader in ASP.Net/JQuery: "Add Files" button not functioning post image upload操作

Hello, I've been utilizing the PLUploader controller for ASP.NET in C#. Initially, it works as intended, but after uploading files, the "add files" button becomes disabled or stops working, preventing me from adding more images. Can anyone offer assi ...

Meteor is failing to update the data in MongoDB

I have encountered an issue with the following code snippet: Nodes = new Meteor.Collection("nodes"); [...] Template.list.events({ 'click .toggle': function () { Session.set("selected_machine", this._id); Nodes.update(Session.get("s ...

Get the desired text following the second <br> tag using jQuery

I am trying to identify a specific string that comes after the second occurrence of <br> tag and then check if this string contains any numbers. If there are no numbers present, I want an alert to be shown. The code for performing this action is func ...

Having trouble with React Testing Library throwing an error every time I try to use fireEvent on an input text?

When attempting to utilize the "fireEvent" method from React Testing Library, I encountered an error as shown below: https://i.sstatic.net/ExH4u.png MainSection.test.js: test('Verifying SearchBar functionality', async () => { render(< ...

The Google Books API has reached its limit for requests

Encountering a rate limit exceeded error from the Google Books API while using this demo: To reproduce, open the developer console in Chrome and perform some searches. The rate limit errors will be displayed in the console. [],"lazyUpdate":null},"status" ...

Importing dynamic NodeJS modules from one module

ModuleA src index.js modules utility.js ModuleB src framework activities activity.js ModuleA serves as the main "runnable" module in this setup, while ModuleB acts as a framework li ...

Issue with jqLite's .triggerHandler() functionality not behaving as anticipated

I'm having an issue with a piece of code that uses triggerHandler. The event is being called correctly, but it's not working as expected. Below is the code snippet and a link to a jsFiddle : HTML: <body ng-app="app"> <button box-cr ...

Smooth Div Scroll experiencing display issues

Trying to integrate the smooth div scroll, specifically the "Clickable Logo Parade" found at: Successfully implemented it on a blank page exactly as desired, but encountering issues when inserting it into the current layout. Could something be causing int ...

Leveraging Jest for mocking "import * as" operations

Is there a way to effectively mock this specific type of import using jest? import * as some from 'some-package'; ...

What is the process of saving a model with @tensorflow/tfjs-node version 2?

I've been struggling with setting up the save handler to save my model. I've scoured through various platforms like stack overflow and GitHub, but haven't had any luck. Help! Any guidance would be greatly appreciated!!! :) Below is a snipp ...

Make the minimum height of one div equal to the height of another div

My query is somewhat similar to this discussion: Implementing a dynamic min-height on a div using JavaScript but with a slight twist. I am working on a dropdown menu within a WordPress site, integrated with RoyalSlider. The height of the slider div adjust ...

Use AppScript to exclude the first row (which contains the column names) when filtering a table

Considering the limitations of Google Sheets with the ImportRange function, I decided to develop an AppScript as a replacement. Although I am new to JavaScript, here is what I have so far: function My_ImportRange() { var clearContent = SpreadsheetApp.ge ...

A Step-by-Step Guide to Successfully Clicking on a Checkbox Using Selenium and Python

Hello everyone, I'm facing an issue with clicking a checkbox. Here is the code for the checkbox: <label class="has-checkbox terms"><input name="order[terms]" type="hidden" value="0" /><input class="checkbox" type="checkbox" value=" ...

Enlarging the current division while reducing the size of the others when hovering

Currently, I am working on a school project that involves creating a slideshow on a webpage. However, I have reached a point where I am unsure of how to proceed. Here is the progress I have made so far: body { background-color: #252525; } #wrapper { ...

A lone function making two separate calls using AJAX

I have a function that includes two Ajax Get calls. Each call has a different function for handling success. function get_power_mgt_settings() { window.mv.do_ajax_call('GET',power_mgt.get_spin_down_url{},'xml',true,show ...

Tips on capturing JSON data for export and sending it to a specific URL

After implementing the recommended code changes, I still cannot see any updates on the specified WordPress page - . It appears that there may be a login information or other issue preventing me from viewing the changes. Here is the updated code: // New ...

Discovering the source of a request payload

Is it possible for me to locate the source of a single item in the request payload using Chrome DevTools, even though I am unsure how it was created? Is there any way for me to find this information? ...