I need to count the occurrence of specific values of a property, grouped by the value of another property. I got working code, but I feel like it can be done more generically.
First off I have two constant arrays. I have a constant with years and a constant with the different possibilities of the values. A third array (myArray) is an array that's formed by a REST call.
const properties = ["a", "b", "c"]
const years = [2015, 2016, 2017, 2018]
let myArray = [
{ date: 2015, prop1: "a" },
{ date: 2015, prop1: "b" },
{ date: 2016, prop1: "b" },
{ date: 2016, prop1: "a" },
{ date: 2016, prop1: "c" },
{ date: 2017, prop1: "b" },
{ date: 2017, prop1: "a" },
{ date: 2017, prop1: "a" },
{ date: 2017, prop1: "b" },
{ date: 2017, prop1: "b" },
{ date: 2018, prop1: "c" },
{ date: 2018, prop1: "b" },
]
Next I have my function. This looks like this.
function doClick() {
let countArray = [];
let counta = 0;
let countb = 0;
let countc = 0;
for (let i = 0; i < years.length; i++) {
let currentYear = years[i]
for (let x = 0; x < properties.length; x++) {
let currentProperty = properties[x];
for (let z = 0; z < myArray.length; z++) {
if (myArray[z].date === currentYear && myArray[z].prop1 === currentProperty) {
switch (currentProperty) {
case "a":
counta++;
break;
case "b":
countb++;
break;
case "c":
countc++;
break;
}
}
}
}
let obj = {
'year': currentYear,
'a': counta,
'b': countb,
'c': countc
}
countArray.push(obj)
counta = 0;
countb = 0;
countc = 0;
}
console.log(countArray)
}
This logs an array which can I can use.
0: {year: 2015, a: 1, b: 1, c: 0}
1: {year: 2016, a: 1, b: 1, c: 1}
2: {year: 2017, a: 2, b: 3, c: 0}
3: {year: 2018, a: 0, b: 1, c: 1}
But the constant array properties is in real live much bigger. So I would like to get rid of the hardcoded cases in the switch statement and the lets counta, countb and countc and make it more flexible.
So can anyone help me get this piece of code better?
Thanks!