Table of contents
1.
Introduction
2.
Why This Function is Used
3.
Syntax, Parameter and Return Value
3.1.
Syntax: 
3.2.
Parameters:
3.3.
Return Value:
4.
Examples 
4.1.
Filtering Numbers:
4.2.
JavaScript
4.3.
Objects with Specific Properties:
4.4.
JavaScript
4.5.
Using a Complex Predicate Function:
4.6.
JavaScript
4.7.
Filtering Based on a List of Values:
4.8.
JavaScript
5.
Frequently Asked Questions 
5.1.
Can _.filter() be used on non-array collections?
5.2.
How does _.filter() handle undefined or null values?
5.3.
Is _.filter() efficient for large datasets?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.filter() Method

Author Gaurav Gandhi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Filtering collections based on specific criteria is a fundamental task in JavaScript, and Lodash enhances this capability with its _.filter() method. This method creates an array of elements that pass a test implemented by a provided function, proving invaluable in data processing and manipulation. 

Lodash _.filter() Method

This article will explore _.filter(), its syntax, and practical use cases, supplemented with examples and FAQs.

Why This Function is Used

The _.filter() function is employed to selectively extract elements from a collection (array or object) that meet certain criteria defined by a predicate function. This is essential in scenarios like data analysis, UI rendering, and processing datasets, where extracting a subset based on specific conditions is required. It streamlines the process of segregating data, allowing for more targeted and efficient data handling.

Syntax, Parameter and Return Value

Syntax: 

_.filter(collection, [predicate=_.identity])

Parameters:

  • collection (Array|Object): The collection to iterate over.
     
  • [predicate=_.identity] (Function): The function invoked per iteration.

Return Value:

 (Array) - Returns the new filtered array.

Examples 

Filtering Numbers:

  • JavaScript

JavaScript

var _ = require('lodash');

var numbers = [1, 2, 3, 4, 5, 6];

var evenNumbers = _.filter(numbers, n => n % 2 === 0);

console.log(evenNumbers);
You can also try this code with Online Javascript Compiler
Run Code

Output: 

[2, 4, 6]


This example demonstrates filtering an array to extract even numbers.

Objects with Specific Properties:

  • JavaScript

JavaScript

var users = [{ 'user': 'barney', 'active': true },

            { 'user': 'fred', 'active': false },

            { 'user': 'pebbles', 'active': true }];

var activeUsers = _.filter(users, {'active': true});

console.log(activeUsers);
You can also try this code with Online Javascript Compiler
Run Code

Output: 

[{ 'user': 'barney', 'active': true }, { 'user': 'pebbles', 'active': true }]


Here, _.filter() is used to retrieve objects that have a specific property value.

Using a Complex Predicate Function:

  • JavaScript

JavaScript

var products = [{ 'name': 'apple', 'type': 'fruit', 'quantity': 5 },

               { 'name': 'carrot', 'type': 'vegetable', 'quantity': 0 },

               { 'name': 'banana', 'type': 'fruit', 'quantity': 3 }];

var availableFruits = _.filter(products, p => p.type === 'fruit' && p.quantity > 0);

console.log(availableFruits);
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

[{ 'name': 'apple', 'type': 'fruit', 'quantity': 5 }, { 'name': 'banana', 'type': 'fruit', 'quantity': 3 }]


An example showing filtering based on more than one condition.

Filtering Based on a List of Values:

  • JavaScript

JavaScript

var values = [1, 2, 3, 4, 5];

var toFilter = [2, 4];

var filteredValues = _.filter(values, v => !toFilter.includes(v));

console.log(filteredValues);
You can also try this code with Online Javascript Compiler
Run Code

Output: 

[1, 3, 5]


Demonstrates filtering out values based on a list of undesired elements.

Frequently Asked Questions 

Can _.filter() be used on non-array collections?

Yes, it works on objects too, creating an array of values that pass the predicate test based on the object's properties.

How does _.filter() handle undefined or null values?

Undefined or null values are treated like any other value; if they meet the predicate condition, they will be included in the result.

Is _.filter() efficient for large datasets?

While efficient for most datasets, performance depends on the complexity of the predicate function and dataset size; testing for specific cases is recommended.

Conclusion

Lodash's _.filter() method is a robust and versatile tool for extracting subsets of data from collections based on specified criteria. It streamlines data processing, enabling more precise and efficient data handling in JavaScript. The method's flexibility and ease of use make it an essential part of a JavaScript developer's toolkit.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass