Apurv Chaudhary
Apurv Chaudhary

Reputation: 1795

how to Group By Array in Angular 4 OR 5?

i got this type of array, and i want to group by only one column (first_name) from whole array,

[
   {
     first_name: "Apurv",
     date: "2018-01-22",
     is_present: "1", 
   }
   {
     first_name: "Lucky",
     date: "2018-01-22",
     is_present: "0", 
   }
   {
     first_name: "Apurv",
     date: "2018-01-20",
     is_present: "0", 
   }
   {
     first_name: "Lucky",
     date: "2018-01-20",
     is_present: "1", 
   }
]

so how can i group by this array from "component"?

Upvotes: 2

Views: 17235

Answers (1)

D C
D C

Reputation: 728

var data = [
   {
     first_name: "Apurv",
     date: "2018-01-22",
     is_present: "1", 
   },
   {
     first_name: "Lucky",
     date: "2018-01-22",
     is_present: "0", 
   },
   {
     first_name: "Apurv",
     date: "2018-01-20",
     is_present: "0", 
   },
   {
     first_name: "Lucky",
     date: "2018-01-20",
     is_present: "1", 
   }
];

var groupByName = {};

data.forEach(function (a) {
    groupByName [a.first_name] = groupByName [a.first_name] || [];
    groupByName [a.first_name].push({ date: a.date, is_present: a.is_present });
});

console.log(groupByName);

Upvotes: 11

Related Questions