Skip to content
Advertisement

Javascript Equivalent to C# LINQ GroupBy

This is a follow up question to the following question:

Javascript Equivalent to C# LINQ Select

We are using Angular 2 + TypeScript:

I have an Array of objects. Each object in the array include a property called ‘StudentType’.

I need to run a C# LINQ style query that extract a list of StudentType in the array and number of array members with that particular type.

While I can do an old school loop and do this, I wonder if there is a better way of doing this, like what C# LINQ GroupBy offers.

Since we are using Angular 2, the use of JQuery is not allowed by the project leads.

Advertisement

Answer

I just made up some studentType values for testing but you can use Array.prototype.reduce() to iterate over each element of the input array and add or manipulate properties of an accumulator object.

let arr = [{
    studentType: 'freshman'
  },
  {
    studentType: 'senior'
  },
  {
    studentType: 'sophomore'
  },
  {
    studentType: 'freshman'
  },
  {
    studentType: 'junior'
  },
  {
    studentType: 'senior'
  },
  {
    studentType: 'sophomore'
  },
  {
    studentType: 'freshman'
  },
  {
    studentType: 'sophomore'
  },
  {
    studentType: 'freshman'
  }
];

let result = arr.reduce((prev, curr) => {
  isNaN(prev[curr.studentType]) ? prev[curr.studentType] = 1 : prev[curr.studentType]++;
  return prev;
}, {});

console.log(result);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement