Tuesday, December 31, 2024
Google search engine
HomeLanguagesJavascriptCollect.js only() Method

Collect.js only() Method

The only() method is used to return the items from the given collection with the specified keys. It takes the key as a parameter and returns the item mapped with that key.

Syntax:

collect(array).only(key)

Parameters: The collect() method takes one argument that is converted into the collection and then only the () method is applied to it. The only() method holds the key as a parameter.

Return Value: This method returns the items from the given collection with the specified keys.

Module Installation: Install collect.js module using the following command from the root directory of your project:

npm install collect.js

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

Example 1: Filename: index.js

Javascript




// Requiring the module
const collect = require('collect.js');
  
// Sample values array
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  
// Creating collection object
const collection = collect(arr);
  
// Function call
const only_val = collection.only([2, 5, 25]);
  
// Printing the values
console.log(only_val.all());


Run the index.js file using the following command:

node index.js

Output:

[ 2, 5 ]

Example 2: Filename: index.js

Javascript




// Requiring the module
const collect = require('collect.js');
  
// Creating collection object
const collection = collect({
    name: 'Rahul',
    dob: '25-10-96',
    section: 'A',
    score: 98,
});
  
// Function call
const only_val = collection.only(['name', 'dob']);
  
// Printing the values
console.log(only_val.all());


Run the index.js file using the following command:

node index.js

Output:

{ name: 'Rahul', dob: '25-10-96' }

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