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 ]