The where() function is used to filter the collection by a given key or value contained within the given array. In JavaScript, the array is first converted to a collection and then the function is applied to the collection.
Syntax:
data.where('key')
Parameters: This function accepts a single parameter as mentioned above and described below:
- Key: This parameter holds the key name that defines the value of that key.
Return value: Return the collection with a key value that was mentioned.
Below examples illustrate the where() function in collect.js:
Example 1: Here in this example, we take a collection and then using the where() method we have returned filtered collection using the key.
Javascript
// It is used to import collect.js library const collection = collect([ { Book: 'Let US C' , price: 2000 }, { Book: 'Begin Python' , price: 1000 }, { Book: 'Learn the DEV' , price: 1500 }, ]); const filtered = collection.where( 'price' , [1000, 1500]); filtered.all(); |
Output:
[ { Book: 'Begin Python', price: 1000 }, { Book: 'Learn the DEV', price: 1500 } ]
Example 2:
Javascript
// It is used to import collect.js library const collect = require( 'collect.js' ); const Input = collect([ new Year( '1980' ), new Year( '2020' ), new Year( '2025' ), ]); const output = Input.where( 'Year' ,[2000, 2025]); console.log(output.all()); |
Output:
[ new Year('2025') ]
Reference: https://collect.js.org/api/where.html