Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptCollect.js flatMap() Method

Collect.js flatMap() Method

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 ]

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

Most Popular

Recent Comments