Working with filters

2019 January, 25th

In this Javascript tutorial, we shall take a look at working with filters. It is part of a four part series in the next few months covering functional programming in Javascript.

You are encouraged to take a look at the previous tutorial on map() function before attempting this.

In the post before we had an array that looked like the one you see below with some songs in it. We shall use it to do some Javascript operations.

1const songs = [
2 {
3 id: 1,
4 timesListened: 1,
5 title: "Doin' Time",
6 artist: "Lana Del Rey",
7 },
8 {
9 id: 2,
10 timesListened: 4,
11 title: "somethingfartoogoodtofeel",
12 artist: "The Japanese House",
13 },
14 {
15 id: 3,
16 timesListened: 2,
17 title: "Eastside",
18 artist: "Benny Blanco, Halsey, Khalid",
19 },
20 {
21 id: 4,
22 timesListened: 10,
23 title: "Everybody Hurts",
24 artist: "Jasmine Thompson",
25 },
26 {
27 id: 5,
28 timesListened: 3,
29 title: "Team",
30 artist: "Lorde",
31 },

Filter Syntax

The filter() method returns a new aray with all elements that pass a condition implement by the provided function.

1const array = anotherArray.filter(callback)

A callback is a special kind of Javascript function (usually without a name to it) that is used by inbuilt or custom functions when another function has finished executing.

How would you extract only the names of songs that have been played more than 3 times?

Using map() together with filter() and arrow functions.
1const artists = songs
2 .filter(song => song.timesListened > 3)
3 .map(song => song.artist)

An alternative way of doing this:

1const artists = songs
2 .filter(function(song) {
3 return song.timesListened > 3
4 })
5 .map(function(song) {
6 return song.artist
7 })


Get the latest posts for in your inbox, every week. We make it super easy to keep up with some interesting discoveries and challenges of working developers along the week.

We've used Linode, a web hosting platform, for both this site and other projects for the last 15 years. It does not disappoint!

Simplify your cloud infrastructure with their Linux virtual machines and robust set of tools to develop, deploy, and scale your modern applications faster and easier.

Check them out!
Who are we?

Coder in 90 provides developers with bite sized courses for thousands of developers around the world.

Β© 2014 - 2020 Coder in 90
a Smartywak service

Built with ❀ from πŸ‡ͺπŸ‡ͺπŸ‡ͺπŸ‡ΈπŸ‡ΈπŸ‡ͺ