2

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"?

Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92
Apurv Chaudhary
  • 1,672
  • 3
  • 30
  • 55
  • what do u mean group by? – Ayush Gupta Jan 22 '18 at 07:11
  • @AyushGupta i don't want to repeat "first_name", you can see in the above array first_name is repeated. – Apurv Chaudhary Jan 22 '18 at 07:14
  • https://github.com/Chalarangelo/30-seconds-of-code#groupby. Note that this has absolutely nothing to do with Angular. It's a pure JavaScript question. – JB Nizet Jan 22 '18 at 07:15
  • From both of the same name, do you want to show the first record? o there is a condition to pick from those two? – Nestor Jan 22 '18 at 07:17
  • @Nestor i want both array record but want 'first_name' only one time. – Apurv Chaudhary Jan 22 '18 at 07:23
  • https://stackoverflow.com/questions/14446511/what-is-the-most-efficient-method-to-groupby-on-a-javascript-array-of-objects – Eliseo Jan 22 '18 at 07:25
  • Possible duplicate of [What is the most efficient method to groupby on a JavaScript array of objects?](https://stackoverflow.com/questions/14446511/what-is-the-most-efficient-method-to-groupby-on-a-javascript-array-of-objects) – Jota.Toledo Jan 22 '18 at 08:10

1 Answers1

11
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);
D C
  • 708
  • 1
  • 6
  • 17