Can the information from duplicate labels be combined into a single column in Chart Js?

Suppose we have an array like ['05/Feb/2019', '05/Feb/2019', '05/Feb/2019', '01/Feb/2019'] for Labels and another array with values like ['2', '5', '7', '4']. Is there a way to display only one column for all the elements '05/Feb/2019' while summing up their corresponding values in that column?

CHART JS CODE SNIPPET

myChart = new Chart(document.getElementById("canvas"),{
    "type":temp.type,
    "data":{
        "labels":column_a,
        "datasets":[{
            "label":label_b,
            "data":column_b,
            "spanGaps": true,
            "fill":false,//true for charts like radar and polar area
            "backgroundColor":["rgba(255, 99, 132, 0.4)","rgba(255, 159, 64, 0.4)","rgba(255, 205, 86, 0.4)","rgba(75, 192, 192, 0.4)","rgba(54, 162, 235, 0.4)","rgba(153, 102, 255, 0.4)","rgba(201, 203, 207, 0.4)"],
            "borderWidth":1
            }
            ]},
            "options":{
                tooltips: {
                    callbacks: {
                        label: (tooltipItem, myChart) => {
                            const realValue = myChart.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
                            //const customValue = realValue.toFixed(2).replace(".", ",") + '%';
                            const customValue = realValue.toFixed(2).replace(".", ",");
                            const label = myChart.labels[tooltipItem.index] + ':';
                            return label + customValue;
                            }
                        }
                    },
                "scales":{
                    "yAxes":[{
                        "gridLines":{display:false},
                        "ticks":{
                            "suggestedMin":0,
                            "max":max_value_1
                        }}]}
                        }});
window.myChart = myChart

Answer №1

If you're looking to achieve this, consider utilizing the reduce function. Hopefully, this will provide the assistance you need!

 let labels = ['10/Mar/2019', '15/Mar/2019', '20/Mar/2019', '01/Mar/2019'];
    let values = ['3', '6', '8', '2'];

    let result = labels.reduce(function(acc, label, index) {
        if(!acc.hasOwnProperty(label)) {
            acc[label] = 0;
        }
        console.log(acc);
        acc[label] += Number(values[index]);
         return acc;
    },{});

    let uniqueLabels = Object.keys(result);
    let uniqueValues = Object.values(result);

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

Am I following the right approach for implementing Dependency Injection in Node.js?

Recently embarking on a new node project, I encountered a dependency injection issue with my fresh module as a Test-Driven Developer. Here's how I resolved the problem using an approach that involves vows for BDD testing and Sinon. The module in ques ...

Top tip: Utilize jQuery for the most effective method of adding content to the HTML of a paragraph situated

One interesting challenge I'm facing involves a textarea that stores dynamic HTML content within paragraph (p) tags. Initial HTML: <textarea rows='7' class='form-control' id='comments'><p>My variable HTM ...

Display various selected checkbox options as text through the use of jQuery (with changing values)

Show Unique Selected Multiple checkbox values as text. It's not a repetition because I have thoroughly looked for it. https://i.sstatic.net/l1Af4.png Dynamic Form inputs: <div class="form-group">Eligible Branch <select id="eligiblebranc ...

Issues with passing parameters in JavaScript

I am facing an issue while passing multiple variables from a PHP page to a JavaScript function. Only the first parameter seems to be passed successfully. In the PHP code, the script is being called like this: <? $sdate = 0; $edate = 2; ?> <scrip ...

Link clicking event fails to trigger button clicking event on initial attempt in Internet Explorer. However, it works successfully on the second click

I'm feeling frustrated with a situation on my web page. I have a div that opens up in colorbox when clicked. Inside the div, there are links that should trigger an event in the code below. This event is meant to fill a hidden field and then click a se ...

What is the best way to activate Google Maps API functions with the gMap jQuery plugin?

Is there a way to call the native Google Map API's "resize" method after initializing the gMap plugin for jQuery? According to the documentation, I am setting up my map element like this: var defaults = { latitude: 0, longitude: 0, zoom: ...

What is the method for adding data to a table without utilizing an ID field?

Here is the code I have written: This table contains details of the candidates: <table id="candidates-table" class="table table-striped table-bordered"> <thead class="thead-dark"> <tr> <th scope="col">Candidate Picture ...

When a certain condition is met, the function can be stopped using clearInterval

Is there a way to stop the setInterval function if a specific condition is met in my code? Here is the code snippet: var checkRecordlock = function() { jQuery.ajax({ url: "http://localhost/project/crl/Mzk=" }).done(function(data) { var is_loc ...

The state remains consistent when utilizing useContext

hello I am currently working on creating a menu toggle in React using the useContext hook. I have set up a variable with an initial value of false, but used createContext and useState to initialize it as true. // Implementing useMenu Context import React, ...

Utilizing an external link to dynamically modify the zoom level of a Google map

I've been struggling for hours to adjust the zoom level of a Google map using an onClick JavaScript function. It seems like my variable "map" is inside the initialize function of the map, which might be causing it not to work, but I'm not complet ...

Eliminate a member from a JSON array

I saved the data in my array as a JSON array in the database. Here is how it looked: ["1","2","3"] When I retrieved the information from the database, I attempted to remove the third element "2" while keeping the same structure. This was the code I used ...

Using the Jquery .on(change) event on a <select> input will only alter the first row

I need help with a table that allows users to add rows. Within the table, there is a select input that triggers an ajax call to update values in another select field. The issue I'm facing is that when a new row is added, the .on(change) event affect ...

javascript batch insert new key values

Is there a more elegant way to set multiple keys of an array in JavaScript? The current code may not be aesthetically pleasing, but it seems to be the only solution that works. var listData = []; listData['today'] = []; listData['data1&a ...

Creating a Social Media Platform with JavaScript, Bootstrap, JQuery, PHP, and Mysqil

I am currently in the process of developing a social networking platform that will have similar features as Instagram. Users will be able to log in, create posts, leave comments, like content, share posts, and send data to a server for storage or display p ...

Combine the values of properties in an object

I have a JavaScript object that contains various properties with string values. I want to concatenate all the property values. Here's an example: tagsArray["1"] = "one"; tagsArray["2"] = "two"; tagsArray["Z"] = "zed"; result = "one,two,zed" To prov ...

Discovering the number nearest to zero

I am facing a challenge where I have an array of integers and need to identify the integer closest to zero (positive integers are considered closer than negative ones). Below is the code snippet that I have been working on: public class CloseToZero { ...

Instructions on how to extract a specific timestamp from a video and utilize it to initiate an event

Is there a way to trigger an event or animation at a specific time in a video or frame of the video? For instance, I want text to appear when a video reaches 30 seconds. I've experimented with currentTime, tried using loadeddata, and attempted to u ...

How can I resolve a 404 error in JavaScript when trying to run a PHP script using XMLHTTPRequest and the file path is not found?

Every time I click the button on the user interface to trigger the Javascript communication with PHP in order to display a "Hello world" page, I keep receiving a "{"timestamp":"2021-06-10T20:14:59.671+00:00","status":404,"error":"Not Found","message":"","p ...

Creating MySQL query results in Node.js manufacturing process

I am looking to format the MySQL result in Node.js in a specific way. The desired result format should look like this: [ { "m_idx" :1 , "contents" : { "m_name" : "a", ...

How to Retrieve a Remote File in Angular using $http.get() with OAuth Authentication

I have a unique situation where my users possess private files that require downloads by authenticated users. The server I am using initially downloads a file from S3 utilizing its own set of S3 app_id and secret_token credentials. Once the file has been d ...