Friday, June 19, 2026
HomeLanguagesJavascriptCollect.js mapToGroups() Method

Collect.js mapToGroups() Method

The mapToGroups() method is used to iterate through the collection elements and passes each value of collection into the given callback function.

Syntax:

collect(array).mapToGroups(callback)

Parameters: The collect() method takes one argument that is converted into the collection and then mapToGroups() method is applied on it. The mapToGroups() method holds the callback function as a parameter.

Return Value: This method returns the collection elements according to given callback.

Below example illustrate the mapToGroups() method in collect.js:

Example 1:

Javascript




const collect = require('collect.js');
  
let obj = [{
    name: 'Ashok',
    score: 75
},
{
    name: 'Rakesh',
    score: 86
},
{
    name: 'Rajesh',
    score: 56
},
{
    name: 'Rakesh',
    score: 98
}];
  
const collection = collect(obj);
  
const sequence = collection.mapToGroups(
    (element) => [element.name, element.score])
  
console.log(sequence.all());


Output:

{ Ashok: [ 75 ], Rakesh: [ 86, 98 ], Rajesh: [ 56 ] }

Example 2:

Javascript




const collect = require('collect.js');
  
let obj = [
    {
        name: 'Rahul',
        dob: '25-10-96',
    },
    {
        name: 'Aditya',
        dob: '25-10-96',
    },
    {
        name: 'Abhishek',
        dob: '16-08-94',
    },
    {
        name: 'Rahul',
        dob: '25-10-96',
    },
];
  
const collection = collect(obj);
  
const sequence = collection.mapToGroups(
    (element) => [element.dob, element.name])
  
console.log(sequence.all());


Output:

{
  '25-10-96': [ 'Rahul', 'Aditya', 'Rahul' ],
  '16-08-94': [ 'Abhishek' ]
}
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

1 COMMENT

Most Popular

Dominic
32516 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6898 POSTS0 COMMENTS
Nicole Veronica
12014 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12110 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6965 POSTS0 COMMENTS