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


Contact Us