Saturday, December 13, 2025
HomeLanguagesJavascriptCollect.js firstWhere() Method

Collect.js firstWhere() Method

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 }
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

Dominic
32446 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6814 POSTS0 COMMENTS
Nicole Veronica
11952 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12030 POSTS0 COMMENTS
Shaida Kate Naidoo
6949 POSTS0 COMMENTS
Ted Musemwa
7200 POSTS0 COMMENTS
Thapelo Manthata
6897 POSTS0 COMMENTS
Umr Jansen
6882 POSTS0 COMMENTS