blog post

How to Filter Arrays in JavaScript: A Comprehensive Guide

Introduction

In this blog post you'll dive into various techniques to filter arrays in JavaScript with practical examples to enhance your coding toolkit. Array filtering in JavaScript allows you to create a new array from an existing one, containing only elements that match a given condition.

Using the filter Method

The filter method is the most common function to filter an array. It calls a provided callback function once for each element in an array, and creates a new array of all the values for which the callback returns a true value. Let's explore an example on how to get odd numbers from the array:

javascript
const numbers = [1, 2, 3, 4, 5]; const oddNumbers = numbers.filter(number => number % 2 !== 0); console.log(oddNumbers); // Output: [1, 3, 5]

Here a function number => number % 2 !== 0 is called to test each array element if it matches the odd number condition.

Filtering array of objects

Filtering becomes particularly powerful when dealing with arrays of objects, enabling complex data manipulations based on object properties. Let's explore an example on how to filter products by their price:

javascript
const products = [ { name: "Laptop", price: 1000 }, { name: "TV", price: 1500 }, { name: "Soundbar", price: 200 } ]; const expensiveProducts = products.filter(product => product.price >= 1000); console.log(expensiveProducts); // Output: [{ name: "Laptop", price: 1000 }, { name: "TV", price: 1500 }]

Here a function product => product.price >= 1000 can use all the properties of products object for filtering.

Complex filtering functions

For more complex scenarios, you can define a custom filtering function to encapsulate the filtering logic. Let's explore an example on how to filter products to get large and expensive ones:

javascript
function getLargeAndExpensiveProducts(product) { const LARGE_SIZE_THRESHOLD = 3; const EXPENSIVE_PRODUCT = 100; return product.size > LARGE_SIZE_THRESHOLD && product.price > EXPENSIVE_PRODUCT; } const products = [ { name: "Compact Chair", price: 99, size: 2 }, { name: "Large Desk", price: 250, size: 3 }, { name: "Sofa", price: 500, size: 5 }, { name: "Bookshelf", price: 150, size: 4 } ]; const largeAndExpensiveProducts = products.filter(getLargeAndExpensiveProducts); console.log(largeAndExpensiveProducts); // Output: [{ name: "Sofa", price: 500, size: 5 }, { name: "Bookshelf", price: 150, size: 4 }]

Here a filter function received a defined callback function as an argument that accepts one parameter: a single product. This function is called for every product and must return a boolean value indicating whether a product matches a given condition or not.

Combining filter with Other Array Methods

You can perform complex data transformations and analyses when combining filter with other array methods such as map and reduce.

Combining filter and map

Combining filter and map allows you to filter your data to only the relevant elements and then transform those elements. Suppose you have an array of products where you want to find only the expensive ones and then create a list of their names:

javascript
const products = [ { name: "Laptop", price: 1200 }, { name: "Phone", price: 700 }, { name: "Tablet", price: 400 }, ]; const expensiveProductNames = products .filter(product => product.price > 500) .map(product => product.name); console.log(expensiveProductNames); // Output: ["Laptop", "Phone"]

map function performs a transformation of each array element and returns a new array. You can use this function to extract a single property or create another object.

Combining filter and reduce

While filter selects the relevant items from an array, reduce can take those items and combine them into a single value, such as a sum or a composite object. Let's calculate the total price of the expensive products only:

javascript
const products = [ { name: "Laptop", price: 1200 }, { name: "Phone", price: 700 }, { name: "Tablet", price: 400 }, ]; const totalExpensivePrice = products .filter(product => product.price > 500) .reduce((total, product) => total + product.price, 0); console.log(totalExpensivePrice); // Output: 1900 (sum of prices of Laptop and Phone)

In the following example, reduce function accepts 2 arguments: total and product.
product corresponds to each array element and total holds a calculated sum of prices.

A Real-World Example of Analyzing Data

Imagine you're analyzing survey data where users have provided their age and rating (1-5) for a product. Your task is to find the average rating given by adults (age 18 and over).

javascript
const responses = [ { age: 25, rating: 4 }, { age: 17, rating: 3 }, { age: 30, rating: 5 }, { age: 22, rating: 4 }, { age: 16, rating: 4 }, ]; const adultResponses = responses.filter(response => response.age >= 18); const length = adultResponses.length; const averageAdultRating = adultResponses .reduce((total, { rating }) => { return total + rating; }, 0) / length; console.log(averageAdultRating.toFixed(2)); // Output: 4.33

In this example, first, we filter responses to get responses by adults. Then we call a reduce function to calculate the total rating and finally divide it by number of responses to get the average rating. Here as a 2nd parameter of reduce function, { rating } is used to extracts a rating property of the response object for each element of the array.

Summary

In JavaScript the most common way to filter data is using a filter function. You can combine it with map and reduce functions to perform complex data manipulations and analysis.
Combining filter and map allows you to filter your data to only the relevant elements and then transform those elements.
Combining filter and reduce allows you to filter your data to only the relevant elements and then combine them into a single value, such as a sum or a composite object.

Hope you find this blog post useful. Happy coding!

Improve Your .NET and Architecture Skills

Join my community of 2400+ developers and architects.

Each week you will get 1 practical tip with best practises and architecture advice.