DEV Community

Bogdan Varlamov
Bogdan Varlamov

Posted on

JavaScript Array Methods: Understanding `filter`

Image description

After delving into forEach and map, let's examine another powerful JavaScript array method: filter. The purpose of filter is clearly reflected in its name. It filters items in an array based on a condition provided in its callback function. The result is a new array consisting only of items that meet this condition.

A Simple Example

To understand filter in action, let's start with a straightforward example:

const numbers = [-2, 5, 10, -68, 91, 9]

const numbersBiggerThanZero = numbers.filter((n) => n > 0)
console.log(numbersBiggerThanZero) // [5, 10, 91, 9]
Enter fullscreen mode Exit fullscreen mode

In this case, the condition is quite simple: we're looking for numbers greater than zero. However, the criteria can be as complex or as simple as needed.

Applying filter in Real Life

To see how filter can be applied in practical scenarios, let's revisit our online grocery store app, focusing on the today's discounts page.
Imagine receiving an array of products from the server. Each product is an object with name, price, and isOnSale properties. Our task is to filter the items to display only those that are on sale.

const products = [
  {
    name: 'apple',
    price: 6,
    isOnSale: false,
  },
  {
    name: 'chicken fille',
    price: 16,
    isOnSale: true,
  },
  {
    name: 'Almond milk',
    price: 11,
    isOnSale: true,
  },
  {
    name: 'Eggs',
    price: 6,
    isOnSale: false,
  },
  {
    name: 'Bread',
    price: 2,
    isOnSale: false,
  },
  {
    name: 'Mango',
    price: 7,
    isOnSale: true,
  },
]

const productsWithDiscount = products.filter((p) => {
  return p.isOnSale ? p : null // can be any of undefined, 0 or null. Nothing will change.
})

console.log(productsWithDiscount)
// [
//   {name: 'chicken fille', price: 16, isOnSale: true},
//   {name: 'Almond milk', price: 11, isOnSale: true},
//   {name: 'Mango', price: 7, isOnSale: true}
// ]
Enter fullscreen mode Exit fullscreen mode

This example demonstrates filter's utility in selectively displaying items based on a given condition—perfect for showcasing discounted products in our app.

Thanks for hanging out! Hit subscribe for more! đź‘‹

Top comments (1)

Collapse
 
edydeyemi profile image
Edydeyemi

Nice.