Stacked Bar Chart in Plain JS

how to populate a Stacked Bar Chart in plain javascript

get the code from codepen before reading on.

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.

We need to be able to group our original data by month and then sum the sections of each bar. I do all this 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. 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 here and also at Rick Delpo's Educational Website