DEV Community

Cover image for how to populate a Stacked Bar Chart in plain javascript
Rick Delpo
Rick Delpo

Posted on • Edited on • Originally published at javasqlweb.org

how to populate a Stacked Bar Chart in plain javascript

Populating a stacked bar chart using only plain javascript without chart libraries (chart.js) or other utility libraries (lodash /moment.js) is certaintly a challenge but this is a MUST learn for the javascript beginner. Get the code here at my Codepen link https://codepen.io/rickdelpo/pen/KKGQrQv

We need to be able to group our original data by month and then sum the sections of each bar. I do this all in Plain Javascript without any chart libraries. First I use the date object and getMonth method to transform json date strings into their month name. Then we implement array.reduce to sum up 3 products sales values for each month. I then feed arrays into a plain for loop to populate the bar chart.

This tutorial presents a good opportunity to learn about certain array methods

  1. array.reduce ...a bit tricky which is why programmers resort to lodash
  2. array.push
  3. array index and indexOf

We also learn about grouping and summing. Using the javascript Date object we get the month name during each pass of the original array. Then while month name equals its current value we sum other array keys for that particular month grouping. Summing is done in our array.reduce method. The result is an interim array without altering the original array. We can then do some math on the interim array (original array transformed to month groups) to create array values to be passed to our bar chart. PS: the sql equivalent to above is sum() and group by. Above we are using noSQL iterating over a JSON formatted data source.

Why do we need to transform our original data anyway? Two reasons, 1. to be sure the timestamp is in a valid date format, otherwise our native Date object won't work and 2. the data needs to be usable so we can extract summed values into our bar chart.

Also why do we strive to not use any JS libraries? The reason is because they are overkill and slow down our web page load time. There is no good reason to use a library when only a few lines of native javascript will solve our problem. PS, notice we do not use Node either.

Bottom Line, it is much easier to show u my code than to explain steps like above. So in order to fully understand my methodology please download my code from codepen here at https://codepen.io/rickdelpo/pen/KKGQrQv. My code is fully commented step by step for easy understanding.

Thanks for reading and best of luck to all !

more about Rick Delpo can be found at https://howtolearnjava.com and https://javasqlweb.org

Top comments (0)