Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptCollect.js groupBy() Method

Collect.js groupBy() Method

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] ] }
}

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments