Collect.js is a wrapper library for working with arrays and objects which is dependency-free and easy to use. The flatMap() method is used to iterate all the collection elements and pass each collection elements into given callback.
Syntax:
collect(array).flatMap(callback)
Parameters: The collect() method takes one argument that is converted into the collection and then flatMap() method is applied on it. The flatMap() method holds a single parameter callback function.
Example 1: Below example illustrates the flatMap() 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 map_Val = collection.flatMap( Â Â element => element.name.toUpperCase()); Â Â console.log(map_Val.all()); |
Output:
[ 'RAHUL', 'ADITYA', 'ABHISHEK' ]
Example 2:
html
const collect = require( 'collect.js' ); Â Â Â let obj = [ Â Â Â Â { Â Â Â Â Â Â Â Â name: 'Rahul' , Â Â Â Â Â Â Â Â score: 98, Â Â Â Â }, Â Â Â Â { Â Â Â Â Â Â Â Â name: 'Aditya' , Â Â Â Â Â Â Â Â score: 96, Â Â Â Â }, Â Â Â Â { Â Â Â Â Â Â Â Â name: 'Abhishek' , Â Â Â Â Â Â Â Â score: 80 Â Â Â Â }, Â Â Â Â { Â Â Â Â Â Â Â Â name: 'Rahul' , Â Â Â Â Â Â Â Â score: 77, Â Â Â Â }, ]; Â Â Â const collection = collect(obj); Â Â Â const map_Val = collection.flatMap( Â Â element => element.score > 80); Â Â console.log(map_Val.all()); |
Output:
[ true, true, false, false ]