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

Collect.js filter() Method

The filter() method is used to filter the given collection using the given callback function and returns the collection element.

Syntax:

collect(array).filter(callback)

Parameters: The collect() method takes one argument that is converted into the collection and then filter() method is applied on it. The filter() method takes one parameter that holds the value of callback function.

Return Value: This method returns the filtered collection elements.

Below example illustrate the filter() method in collect.js:

Example 1:

Javascript




const collect = require('collect.js');
  
const arr = [2, 4, 5, 6, 8, 9, 10];
  
const collection = collect(arr);
  
const remaining_element = collection
    .filter((val, key) => val % 2 == 0);
  
console.log(remaining_element.all());


Output:

[ 2, 4, 6, 8, 10 ]

Example 2:

Javascript




const collect = require('collect.js');
  
let obj = [
    {
        name: 'Rahul',
        score: 98,
    },
    {
        name: 'Aditya',
        score: 96,
    },
    {
        name: 'Abhishek',
        score: 80
    },
];
  
const collection = collect(obj);
  
const remaining_element = collection
    .filter((val, key) => val.score > 80);
  
console.log(remaining_element.all());


Output:

[ 
    { name: 'Rahul', score: 98 }, 
    { name: 'Aditya', score: 96 } 
]
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