Collect.js mapToGroups() Method
Last Updated :
27 Nov, 2020
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' ]
}
Share your thoughts in the comments
Please Login to comment...