Monday, December 30, 2024
Google search engine
HomeLanguagesJavascriptCollect.js | first() Function

Collect.js | first() Function

The first() function gives the first value of the collection. Simply means it returns the first value or the first method returns the first element in the collection that passes a given condition.  In JavaScript, the array is first converted to a collection and then the function is applied to the collection.

Syntax: 

data.first(e)

Parameters:  This function accepts a single parameter as mentioned above and described below:

  • e : This parameter holds a condition that has to pass by the collection

Return value: Processed value

Below examples illustrate the first() function in collect.js

Example 1: Here in this example, we take a collection and then using the first() function to get first value.

Javascript




// It is used to import collect.js library
  
const collect = require('collect.js');
  
const nums = [0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9];
const data = collect(nums);
  
let value = data.first(e => e =4);
console.log(value);


Output : 

0

Example 2: In this example, we will get the first negative value.

Javascript




// It is used to import collect.js library
  
const collect = require('collect.js');
  
const num = [0 , 1 , 2 , 3 , -4 , 5 , -6 , 7 , 8 , 9];
const data = collect(num);
  
let value = data.first(e => e < 0);
console.log(value);


Output: 

-4

Reference: https://collect.js.org/api/first.html

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