Combining multiple datasets in Javascript with a constant value of [0] to calculate the sum

Being a beginner, I am seeking assistance with my variable chartdata that serves as a basis:


var chartdata = {
  labels: [
    "Bar 1",
    "Bar 2",
    "Bar 3",
    "Bar 4",
  ],
  datasets: [
    {
      label: "Green data",
      type: "bar",
      data: [20, 30, 40, 20]
    },
    {
      label: "Red data",
      type: "bar",
      data: [10, 30, 20, 10]
    },
    {
      label: "Blue data",
      type: "bar",
      data: [20, 20, 20, 20]
    },

Since I have a stacked barchart, I am interested in knowing how I can sum the data points for "Bar 1," which are 20, 10, 20 = 50.

Initially, I attempted using an array, which was as follows:

const array0 = chartdata.datasets[0].data;

console.log(array0.reduce((a, b) => a + b, 0));

...however, this only added 20 + 30 + 40 + 20, encompassing all the data within dataset[0] and similar operations. This meant I could only obtain the sum of all Green data points or others, but not the total sum for an individual stacked bar.

It seemed unattainable to perform an operation like chartdata.datasets[0 to 4].data[always 0]; which would provide the overall value of "Bar 1" on the y-axis.

I attempted to create something using .map, but encountered difficulties in achieving it independently.

Perhaps you, as experts, could offer me a solution that I can immediately execute.

Thank you in advance.

Answer №1

Implement the Array#reduce method to iterate over the chartdata.datasets array.

let chartdata={labels:["Bar 1","Bar 2","Bar 3","Bar 4",],datasets:[{label:"Green data",type:"bar",data:[20,30,40,20]},{label:"Red data",type:"bar",data:[10,30,20,10]},{label:"Blue data",type:"bar",data:[20,20,20,20]},]};
let res = chartdata.datasets.reduce((acc, curr) => acc + curr.data[0], 0);
console.log(res);

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

Troubleshooting Issue: Unable to Retrieve Loaded Record in Ember.js

I am facing an issue with accessing properties to change the header of my RESTAdapter after loading the user. Do you have any ideas why that might be happening? The code snippet in question is as follows: var user = ''; App.MainRoute = Ember.R ...

Javascript behavior during execution can vary from what is observed during debugging

I'm currently facing an issue while trying to debug a script. Everything seems to work fine in debug mode, but not during runtime. Here's the JavaScript function causing trouble: function Add() { ... $('#Value').val($('#V ...

ReactJs - Organize your data with the sort method

In my React application, I have a table that fetches its data from an API. I need to implement sorting for one of the columns. The values in this column are usually strings of numbers but sometimes can be equal to "-" (Dash). Below is the sort function I ...

Vue.js is experiencing an issue with undefined values within computed properties

I have a specific input tag with the model selectedProp: <input type="text" v-model="selectedProp" /> and I need to loop through items in this manner: <div v-for="item of filteredItems">{{item.prop}}</div> Below is the code snippet fo ...

What could be causing my React Router to fail in displaying the content of Home.js?

My <Route> is not functioning as expected The Route leading to the homepage does not show the content from the Home.js file import "./App.css"; import Navbar from "./components/Navbar"; import { BrowserRouter as Router, Route, Ro ...

React-Native - Issue with TypeError: attempting to call a function that is undefined (specifically when using the 'object.map' method)

I've tested everything from the itemList to the reducer and action, it's working fine and successfully deleting the desired item. However, I encountered an error afterwards. I'm not sure where I went wrong. Can someone guide me on what steps ...

Visualizing Data with d3.js Force Chart: Integrating Images with Nodes for Dynamic Animation

After enhancing a force diagram to compare two profiles, I am faced with the challenge of getting the main node to display an image. View comparison here How can I centrally align and size the image correctly while making the thumbnail data from the JSO ...

There is an issue as headers cannot be changed after being set for the client

I am in the process of developing an employee leave management system. Everything runs smoothly until an issue arises when attempting to update the leave status as an admin, and the logged-in account or user does not have admin privileges. There is a midd ...

The IMG onclick event for LinkModalDialog does not function properly on Mozilla browsers

I am currently utilizing the following function: function OpenLinkModal(obj){ var arr=showModalDialog("../../files/list_simple.asp","","dialogHeight: 600px; dialogWidth: 450px; edge: Raised; center: Yes; resizable: Yes; status: Yes; scroll: Yes; help ...

What causes the disparity in the functionality of getServerSideProps between index.js and [id].js in NextJS?

Exploring NextJS and React as part of my e-commerce site development journey has been exciting. However, I encountered a roadblock when trying to connect to an external database that requires real-time updates, making getStaticProps unsuitable for my needs ...

Experiment with catching an exception on variable `v`

In my code, I am using a v-if statement to display an error message in HTML. <div id="error" v-if="showError">Error User or Password</div> data() { return { showError: false, };} When I change the value of showError ...

"Encountered an issue with loading a resource in the inspector within Angular

Using angular's ng-repeat, I am uploading some placeholder content. var app = angular.module("homeApp", []); app.controller("entriesView", function ($scope){ $scope.itemEntry = [ { image: "img/112013-priscilla-600.jpg", title: "y ...

Leverage JavaScript E4X to cleverly rename specific XML elements

Currently, I am using JavaScript to manipulate XML without involving the DOM in a browser context. I need assistance with creating an E4X expression that can rename a list of tags based on a given substring. The challenge is that I may not know the exact t ...

How can I effectively send data from a view to a controller using AJAX in C# using Leaflet?

Every time I attempt to pass data from the view to the controller, I keep receiving an "alert request failed" message. I am uncertain of the datatype for leafletLats and leafletLngs, but they are both arrays derived from coord which is of type LatLng[]. ...

Dynamic Loading of CSS Styles

My style-sheet is saved in this unique location: /opt/lampp/htdocs/project/core/styles/Style.css To load the CSS file using the full directory, considering that the files utilizing it are situated here: /opt/lampp/htdocs/project/client/ The ultimate ob ...

code in html/javascript that is securely implemented for adobe air applications

Creating a desktop application using Adobe Air is my goal, but I have concerns about the security of the HTML/JavaScript source code. My application will feature paid media content, and I am hesitant to expose any URLs associated with it. What methods ca ...

Issue: failure of child element - the provided path is incorrect: "users/[object Object]", when implementing Firebase with Next.js

Having trouble with the identityNumber variable, which is giving an error message stating that a string is required. However, my identity number is already a string. Any assistance would be greatly appreciated. Additionally, the aim is to make the identity ...

Displaying markers on a Google map by fetching data from a MySQL database in PHP

The image attached here serves as an example. You can view it here. Currently, I display locations on a map in an HTML page with static code like: Here is the JavaScript code to load the map on the page: <script type="text/javascript" src="https://ma ...

Leveraging React with axios instead of curl

Can a curl request be made using axios? The curl command is as follows: curl -v 'https://developer.api.autodesk.com/authentication/v1/authenticate' --data 'client_id=1234&client_secret=1234&grant_type=client_credentials&scope=b ...

What is the best way to generate an integer array containing randomly shuffled numbers within a specified range?

Suppose I have an integer array that can hold 10 numbers. This means I can store numbers 0-9 in each index, with each number only appearing once. If I execute the following code: int[] num = new int[10]; for(int i=0;i<10;i++){ num[i]=i; } my array ...