Arrays + functions: filter()

With filter() you can create a new array from an existing one, but contrary to map() you can choose which items you want to include.

How do you choose? In the callback function that filter() accepts, you return true to include that item in the new array.

Suppose you have an array with some numbers:

const a = [1, 2, 3, 4, 5]

and you want to create an even array with just the even numbers.

Here’s how to do that:

const even = a.filter((item) => {
  if (item % 2 === 0) return true
  return false
})

We can write it in a shorter form:

a.filter(item => item % 2 === 0)

This method return an array, so you can assign it to a new variable:

const even = a.filter(item => item % 2 === 0)

even is an array containing [2, 4].

A very good example of filter() in practice is to find a specific element in the array:

const a = [1, 2, 3, 4, 5]
const b = a.filter(item => item === 3).shift()

I used shift() because filter() returns an array, and shift() returns the first item in the array, or undefined if the array is empty.

Another practical example of using filter() is when you want to remove an item from the array. Suppose you want to remove the number 3 from the array:

const a = [1, 2, 3, 4, 5]

const b = a.filter(item => item !== 3)
// [1, 2, 4, 5]

You can also change this slightly to remove multiple items, using includes():

const items = ['a', 'b', 'c', 'd', 'e', 'f']

const valuesToRemove = ['c', 'd']

const filteredItems = items.filter(item => !valuesToRemove.includes(item))

console.log(filteredItems)
// ["a", "b", "e", "f"]

Lessons in this unit:

0: Introduction
1: map()
2: ▶︎ filter()
3: reduce()
4: sort()
5: find() and findIndex()
6: forEach()
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!