DEV Community

Bogdan Varlamov
Bogdan Varlamov

Posted on

1

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! 👋

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (1)

Collapse
 
edydeyemi profile image
Edydeyemi

Nice.

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay