Guide on setting an array as the data for counts in charts.js

I am working with a chart.js graph and I need to assign an array to the data property.

Below is my current code snippet:

datasets: [
    {
      data:[40,56,345,2354],
      backgroundColor: "#007BA7",
      hoverBackgroundColor: "#00CC99"
    }
]

However, I want to use an array that contains a list of products. This is my attempt, but it is not working:

datasets: [
    {
      data: this.lastSeenDeviceCount.forEach(element => {
        element.length
      }),
      backgroundColor: "#007BA7",
      hoverBackgroundColor: "#00CC99"
    }
]

This is the information in the data source:

this.lastSeenDeviceCount.push(activeRecords,offlineRecords, pendingRecords);
// array contains this object
{
    "DeviceID": "52",
    "FriendlyName": "Net RC",
    "UserName": "UserNet",
    "LastSeen": "07/23/2020 23:18:05",
}

Answer №1

Did you give this a shot?

this.lastSeenDeviceCount.map(element => element.length)

Answer №2

Here's a simple breakdown of what's going on:

let devices = []; // an array to hold devices
this.lastSeenDeviceCount.forEach(element => {
  devices.push(element.length)
})

datasets: [
  {
    data: devices,
    backgroundColor: "#007BA7",
    hoverBackgroundColor: "#00CC99"
  }
]

Essentially:

  1. You initialized an empty array
  2. You added values to the array within a loop
  3. Finally, you assigned this array to the chartJs data property to display on the 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

Error message "e.nodename undefined when set to setTimeout" was encountered

I developed a unique piece of code for input boxes located at the top of different tables. By using a class='filt', the table can be filtered based on the inputs provided. However, most of the inputs consist of more than one letter, so I wanted t ...

Controlling ever-changing routes using AngularJS

My AngularJS app (Angular v1) has a secure login system in place. Users who are not authenticated can only access the login page, forgotten password page, and cookie policy. I am utilizing ngRoute as shown below: $routeProvider .when('/login ...

Finding the Closest Element with jQuery's .closest() Method

I'm facing an issue while trying to select an element that is positioned above another element. Specifically, I want to target the nearest occurrence of the .discount-dropdown class that appears above the .discount-type class. Can anyone help me figur ...

Design Pattern of AngularJS/Bootstrap Application

Seeking guidance on structuring a small AngularJS application for a simple stock charts app. As a seasoned developer but new to AngularJS, I am looking for the best approach. App Overview The app includes a left-hand "nav" bar for adding and selecting s ...

IE8 is encountering a null JSON response from the HTTP handler, unlike IE10 and Chrome which are not experiencing this

Here is my JavaScript code snippet: patients.prototype.GetPatient = function(patient_id,callback) { var xmlhttp; var fullpath; try { if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { ...

Angular 2 wrap-up: How to seamlessly transfer filter data from Filter Component to App Component

A filtering app has been created successfully, but there is a desire to separate the filtering functionality into its own component (filtering.component.ts) and pass the selected values back to the listing component (app.ts) using @Input and @Output functi ...

React modal not closing when clicking outside the modal in Bootstrap

I recently utilized a react-bootstrap modal to display notifications in my React project. While the modal functions correctly, I encountered an issue where it would not close when clicking outside of the modal. Here is the code for the modal: import Reac ...

focusing on a specialized format using the serialize() method

Following up on my previous question which was answered so promptly by Meder, there is now an additional query that has arisen while creating a reusable jQuery form submission without redirecting the user. Issue The jQuery serialize() function is applyin ...

MAJOR UPDATE: webpack versions before 5 previously contained polyfills for node.js specifically for 'timers-browserify'

Hey there, I'm encountering the error message below: ./node_modules/xml2js/lib/parser.js:38:17-47 - Error: Module not found: Error: Can't resolve 'timers' in '/Users/differentname/Desktop/workfiles/webdoc/ngx-admin-1/node_modules/x ...

What methods can I use to generate unique paths within a URL for a website, and how can I assign a distinct status to each path?

I have developed a JavaScript program that allows you to draw using canvas. I have now set up a web server with Node.js in order to enable drawing on the website. Each specific drawing will be saved as a unique URL path so that you can resume where you lef ...

The error was thrown at line 883 in the cjs/loader.js file of the

I'm encountering an error when trying to run npm start (I've included a screenshot of the error below) in my Angular project. However, everything works fine when I use ng serve. I've attempted multiple solutions to resolve this issue with ...

Align the body of the table with the header after populating the table with values

Issue : The data in the table body is misaligned with the headers of each column. Solution : var test_insert1 = '<tr>' + '<td class="td-trad-9">762261</td>' + '<td class="td-trad-7">1.16176&l ...

Using JavaScript to access a button from a dropdown list in ASP.NET MVC

I'm trying to use a JavaScript function to trigger the click event of an HTML button when a drop-down list is changed. However, it seems like the correct id is not being found. @using (Ajax.BeginForm("GetReport", "Choices", new AjaxOptions() { ...

Track user engagement across multiple platforms

Looking for solutions to log system-wide user activity in my Electron app. I want to track mouse-clicks and keystrokes to determine if the user is inactive for a certain period of time, triggering a timer reset within the application. I believe I may nee ...

Utilizing AngularJS, implement ng-form and ng-repeat to seamlessly handle input validation and submission actions

Angular 1.6.2 I am experimenting with iterating over elements of a collection inputted by the user, checking their validity, and enabling the submit action if validation passes. I have tried using ng-form for this purpose and have come up with two differ ...

Refining strings to enum keys in TypeScript

Is there a method to refine a string to match an enum key in TypeScript without needing to re-cast it? enum SupportedShapes { circle = 'circle', triangle = 'triangle', square = 'square', } declare const square: string; ...

How to retrieve the correct instance of "this" from a callback function within an array of functions nested inside an object

Trying to access the "helperFunction" from within a function in the "steps" array has been quite challenging. It seems that using "this" does not point to the correct object, and I have been struggling to find the right solution. const bannerAnimation = { ...

Transforming varied JavaScript objects into a serial form

In my application, there is a concept of an interface along with multiple objects that implement this interface in various ways. These objects are created using different factory methods, with the potential for more factories to be added as the application ...

How can I furnish TSC with TypeScript definitions for URI imports in a comprehensive manner?

import Vue from 'https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c5b3b0a085f7ebf0ebf7f4">[email protected]</a>/dist/vue.esm.js' If I submit the above code to TSC for compilat ...

The JSON data response is not being properly displayed on the div element

I am having trouble with the success function in my ajax call. The data is processed correctly in the view and the ajax call works fine, but for some reason, the data is not getting appended to the div. Here is my jQuery: $(document).ready(function() { ...