how to use the groupby function from the underscore library in javascript

The groupBy function provided by the Underscore library in JavaScript allows you to group a collection of items by a specified property or function. The resulting output is a JavaScript object where the keys are the values of the property or the function return value by which the elements are grouped, and the values are arrays containing the elements that belong to each group.

Here's an example of using groupBy to group an array of objects by a property:

index.tsx
const students = [
  { name: 'John', age: 21 },
  { name: 'Jane', age: 19 },
  { name: 'Bob', age: 21 },
  { name: 'Alice', age: 20 },
  { name: 'Joe', age: 19 }
];

const groupedByAge = _.groupBy(students, 'age');

console.log(groupedByAge);
// Output:
// {
//   19: [
//     { name: 'Jane', age: 19 },
//     { name: 'Joe', age: 19 }
//   ],
//   20: [
//     { name: 'Alice', age: 20 }
//   ],
//   21: [
//     { name: 'John', age: 21 },
//     { name: 'Bob', age: 21 }
//   ]
// }
486 chars
26 lines

In this example, we have an array of objects representing students, each with a "name" and "age" property. We use the groupBy function to group the students by their age, resulting in an object with keys representing the distinct ages and values being an array of objects representing the students that belong to the respective age group.

gistlibby LogSnag