Related Articles

Related Articles

Collect.js filter() Method
  • Last Updated : 25 Nov, 2020

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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());

chevron_right


Output:

[ 2, 4, 6, 8, 10 ]

Example 2:

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

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());

chevron_right


Output:

[ 
    { name: 'Rahul', score: 98 }, 
    { name: 'Aditya', score: 96 } 
]

full-stack-img




My Personal Notes arrow_drop_up
Recommended Articles
Page :