[Chartjs]-Grouping the object by key for Chartjs bar chart

6👍

You could use a hash table as reference to the array with the same status and another hash table for indices of the names. then build the labels array and datasets.

var raw = [{ statusId: 0, firstName: "Joe", status: "appealed", count: 1 }, { statusId: 0, firstName: "Jane", status: "approved", count: 100 }, { statusId: 0, firstName: "Smith", status: "approved", count: 63 }, { statusId: 0, firstName: "Mike", status: "approved", count: 63 }, { statusId: 0, firstName: "Ken", status: "approved", count: 35 }, { statusId: 0, firstName: "Kim", status: "approved", count: 193 }, { statusId: 0, firstName: "JoeJoe", status: "approved", count: 1 }, { statusId: 0, firstName: "Jane", status: "closed", count: 1 }, { statusId: 0, firstName: "Joe", status: "concluded", count: 1 }, { statusId: 0, firstName: "Jane", status: "denied", count: 6 }, { statusId: 0, firstName: "Smith", status: "denied", count: 9 }, { statusId: 0, firstName: "Mike", status: "denied", count: 1 }, { statusId: 0, firstName: "Mark", status: "denied", count: 8 }, { statusId: 0, firstName: "Ken", status: "denied", count: 2 }, { statusId: 0, firstName: "Kim", status: "denied", count: 20 }, { statusId: 0, firstName: "Joe", status: "denied", count: 2 }, { statusId: 0, firstName: "Joe", status: "transferred", count: 1 }],
    nameIndices = Object.create(null),
    statusHash = Object.create(null),
    data = { labels: [], datasets: [] };

raw.forEach(function (o) {
    if (!(o.firstName in nameIndices)) {
        nameIndices[o.firstName] = data.labels.push(o.firstName) - 1;
        data.datasets.forEach(function (a) { a.data.push(0); });
    }
    if (!statusHash[o.status]) {
        statusHash[o.status] = { label: o.status, fillcolor: 'f00', data: data.labels.map(function () { return 0; }) };
        data.datasets.push(statusHash[o.status]);
    }
    statusHash[o.status].data[nameIndices[o.firstName]] = o.count;
});

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Leave a comment