Tuesday, December 31, 2024
Google search engine
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

Recent Comments