Collect.js is a wrapper library for working with arrays and objects which is dependency-free and easy to use. The groupBy() method is used to group the given collection items into multiple collections by a given key
Syntax:
collect(array).groupBy(key)
Parameters: The collect() method takes one argument that is converted into the collection and then groupBy() method is applied on it. The groupBy() method holds the key of the object.
Return Value: This method returns the multiple collections grouped by given key.
Example 1: Below example illustrates the groupBy() method in collect.js
html
const collect = require('collect.js'); let obj = [ { name: 'Rahul', score: 98, }, { name: 'Aditya', score: 96, }, { name: 'Abhishek', score: 80 } ]; const collection = collect(obj); const grouped_val = collection.groupBy('name'); console.log(grouped_val.all()); |
Output:
{ Rahul: Collection { items: [ [Object] ] }, Aditya: Collection { items: [ [Object] ] }, Abhishek: Collection { items: [ [Object] ] } }
Example 2:
html
const collect = require('collect.js'); let obj = [ { name: 'Rahul', dob: '25-10-96', section: 'A', score: 98, }, { name: 'Aditya', dob: '25-10-96', section: 'B', score: 96, }, { name: 'Abhishek', dob: '16-08-94', section: 'A', score: 80 }, { name: 'Rahul', dob: '19-08-96', section: 'B', score: 77, }, ]; const collection = collect(obj); const grouped_val = collection.groupBy('dob'); console.log(grouped_val.all()); |
Output:
{ '25-10-96': Collection { items: [ [Object], [Object] ] }, '16-08-94': Collection { items: [ [Object] ] }, '19-08-96': Collection { items: [ [Object] ] } }