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