The first() function gives the first value of the collection.
It returns the first value or the first method returns the first element in the collection that passes a given condition.
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
Example 1: Here in this example, we take a collection and then using the first() function to get first value.
// 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:
0Example 2: In this example, we will get the first negative value.
// 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