Open In App

Collect.js firstWhere() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The firstWhere() method is used to return the first element from a collection with the given key and value pair. It can be used to find any element in an array by only specifying any of the key-value pairs in an object.

Syntax:

collect(array).firstWhere( key, value )

Parameters: The collect() method takes one argument that is converted into the collection and then firstWhere() method is applied to it. The firstWhere() method takes the key and value pair to be searched as arguments.

Return Value: It returns the first element from the collection with the given key and value pair.

The below example illustrates the firstWhere() method in collect.js:

Example 1:

Javascript




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);
  
let first_Val = 
  collection.firstWhere("name", "Rahul");
console.log(first_Val);


Output:

{ name: 'Rahul', score: 98 }

Example 2:

Javascript




const collect = require("collect.js");
  
let obj = [
  {
    name: "Rahul",
    dob: "25-10-96",
    section: "A",
    score: 98,
  },
  {
    name: "Aditya",
    dob: "25-10-96",
    section: "B",
    score: 96,
  },
  {
    name: "Abhishek",
    dob: "16-08-94",
    section: "A",
    score: 80,
  },
  {
    name: "Rahul",
    dob: "19-08-96",
    section: "B",
    score: 77,
  },
];
  
const collection = collect(obj);
  
let first_Val = 
  collection.firstWhere("dob", "25-10-96");
console.log(first_Val);


Output:

{ name: 'Rahul', dob: '25-10-96', section: 'A', score: 98 }


Last Updated : 25 Nov, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads