JavaScript / 3 MIN READ
filter()
Create new arrays based on conditions
From the original Fervor library. Examples may use older package versions.
JavaScript Array filter() Method Tutorial
Introduction
Welcome to the FrOnt3nd Tutorials! In this tutorial, we’ll explore the filter() method, a powerful tool in JavaScript for creating new arrays based on specific conditions. The filter() method allows you to selectively include or exclude elements from an array based on a callback function.
Syntax
The filter() method has the following syntax:
array.filter(callback(element[, index[, array]])[, thisArg]);
Callback Function
The callback function is a crucial part of the filter() method. It’s called for each element in the array and should return a Boolean value. The arguments passed to the callback function are:
element: The current element being processed.index(optional): The index of the current element.array(optional): The array being processed.
The thisArg parameter is optional and sets the value of this when executing the callback function.
Using the filter() Method
The filter() method iterates through each element of an array and applies the callback function. If the callback returns true for an element, that element is included in the new array. If the callback returns false, the element is excluded.
Examples
Filtering Odd Numbers
Consider the following example where we filter out even numbers from an array:
const numbers = [1, 2, 3, 4, 5, 6];
const oddNumbers = numbers.filter(function(number) {
return number % 2 !== 0;
});
console.log(oddNumbers); // Output: [1, 3, 5]
Filtering Objects by Property
You can filter objects in an array based on their property values:
const users = [
{ name: 'Alice', age: 25, gender: 'female' },
{ name: 'Bob', age: 30, gender: 'male' },
// ...
];
const maleUsers = users.filter(user => user.gender === 'male');
console.log(maleUsers);
// Output: [{ name: 'Bob', age: 30, gender: 'male' }, ...]
Filtering Arrays Based on Index
You can filter elements based on their position or index:
const numbers = [1, 2, 3, 4, 5, 6];
const firstThree = numbers.filter((number, index) => index < 3);
console.log(firstThree);
// Output: [1, 2, 3]
const lastThree = numbers.filter((number, index, array) => index >= array.length - 3);
console.log(lastThree);
// Output: [4, 5, 6]
Filtering Arrays with Multiple Conditions
Filtering with multiple conditions is also possible:
const products = [
{ name: 'Widget A', price: 20, inStock: true },
// ...
];
const cheapInStockProducts = products.filter(product => product.price < 50 && product.inStock);
console.log(cheapInStockProducts);
// Output: [{ name: 'Widget A', price: 20, inStock: true }, ...]
Best Practices and Tips
Always Return a Boolean
The callback function should always return a Boolean value. This ensures proper filtering behavior.
Using Arrow Functions for Concise Code
Arrow functions can make your code concise, especially when using filter():
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(number => number % 2 === 0);
Object References
When filtering an array of objects, be cautious with object references:
const people = [{ name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }];
const filteredPeople = people.filter(person => person.age < 30);
filteredPeople[0].age = 27;
console.log(people[0]); // Output: { name: 'Alice', age: 27 }
Chaining with Other Array Methods
You can chain filter() with other array methods like map(), reduce(), and forEach() for complex operations:
const numbers = [1, 2, 3, 4, 5];
const sumOfEvenNumbers = numbers.filter(number => number % 2 === 0).reduce((sum, number) => sum + number, 0);
console.log(sumOfEvenNumbers); // Output: 6
Conclusion
The filter() method is a versatile tool in JavaScript for manipulating arrays based on specific conditions. Whether you’re selecting elements based on values or positions, filtering with multiple conditions, or chaining methods, the filter() method offers endless possibilities. By applying the concepts and best practices covered in this tutorial, you’ll be well-equipped to leverage the power of the filter() method in your programming projects.
For more information, refer to the official MDN documentation.