How to Find the Sum of items Per Year Using Chart Js

1👍

To get your y-axis array, you can use a combination of reduce with an ES6 Map. The idea of a Map is similar to a regular object, it stores key-value pairs. Each key must be unique. You can use .reduce() to accumulate/form your Map, by setting the keys to be the year from your array. If the year is already in the Map, you can increment its value which will hold the number of times that year appears. If the year isn’t in the map, you can add it as a new key with a value of 1 (to indicate that year has been encountered once). You can then get the keys from the map and turn it into an array using Array.from() to get an array of unique years. You can also get the values from the map and convert it into an array to get an array of frequencies. Each index from the xAxis array correspond will correspond to the frequency at the same index (eg: xAxisArr[0] holds "2012", so its frequency will be yAxisArr[0] (same index), which is 6).

const arr = ["2012", "2016", "2011", "2017", "2017", "2012", "2014", "2019", "2019", "2014", "2012", "2016", "2012", "2015", "2013", "2012", "2011", "2008", "2015", "2009", "2011", "2018", "2019", "2017", "2015", "2020", "2016", "2010", "2013", "2017", "2018", "2014", "2014", "2019", "2015", "2019", "2016", "2014", "2015", "2015", "2019", "2009", "2016", "2014", "2015", "2015", "2015", "2016", "2012", "2013"];

const freqMap = arr.reduce(
  (map, year) => map.set(year, (map.get(year) || 0) + 1),
  new Map
);
const xAxisArr = Array.from(freqMap.keys()); // array of unique years
const yAxisArr = Array.from(freqMap.values()); // array of frequencies for each year

console.log("x axis");
console.log(xAxisArr);
console.log("y axis");
console.log(yAxisArr);

Note: I’m assuming that the literal numbers in your array that you provided such as 2015 (rather than "2015" as a string) are typos, so I have converted them in the example above. If they’re not typos you can map your array to strings using .map(String).

Leave a comment