Home » Php » javascript – How to categorize data based on multple variable

javascript – How to categorize data based on multple variable

Posted by: admin February 25, 2020 Leave a comment

Questions:

i want to categorize this json object

    var lists=[{"No":58,"Time":"Feb-2020","Labels":"Mahasiswa","FullName":"Raga"},
{"No":59,"Time":"Feb-2020","Labels":"Mahasiswa","FullName":"Raga"},
{"No":60,"Time":"Feb-2020","Labels":"Umum","FullName":"Raga"},
{"No":61,"Time":"Feb-2020","Labels":"Mahasiswa","FullName":"Raga"},
{"No":62,"Time":"Feb-2020","Labels":"Pelajar","FullName":"Raga"},
{"No":63,"Time":"Feb-2020","Labels":"Umum","FullName":"Rga"},{}];

how to count the occurences of based on time and labels.
for example

let time= [Feb-2020]
let labelsmahasiswa= [3]
let labelsumum= [2]
let labelspelajar= [1]

i have been successfull counting the occurences based on time only with

let count = lists.reduce((newObj, obj) => {
  if(newObj[obj.Time]) {
    newObj[obj.Time] = newObj[obj.Time]+1;
  } else {
    newObj[obj.Time] = 1;
  }

  return newObj;

}, {});

And i return it like this

var lists2 = [[#Time],[#Occurences]];
for(i=0;i<(Object.keys(count).length-1);i++){

    lists2[0].push (Object.keys(count)[i]);
    lists2[1].push (Object.values(count)[i]);

};

When i console.log the lists2

console.log(lists2)
//[[Feb-2020],[6]]

Thank u in advance.

How to&Answers:

You could take an object with Time as key for nested object which contains the counts of Labels.

var lists = [{ No: 58, Time: "Feb-2020", Labels: "Mahasiswa", FullName: "Raga" }, { No: 59, Time: "Feb-2020", Labels: "Mahasiswa", FullName: "Raga" }, { No: 60, Time: "Feb-2020", Labels: "Umum", FullName: "Raga" }, { No: 61, Time: "Feb-2020", Labels: "Mahasiswa", FullName: "Raga" }, { No: 62, Time: "Feb-2020", Labels: "Pelajar", FullName: "Raga" }, { No: 63, Time: "Feb-2020", Labels: "Umum", FullName: "Rga" }, {}],
    result = lists.reduce((r, { Time, Labels }) => {
        if (!Time) return r;
        r[Time] = r[Time] || {};
        r[Time][Labels] = (r[Time][Labels] || 0) + 1;
        return r;
    }, {});

console.log(result);