Becoming a JavaScript Jedi - Mastering the JavaScript Filter

Great content for technologists, entrepreneurs, and content creators


javascript filter
Author: Mensah Alkebu-Lan

Table of Contents #

Prerequisites #

Some familiarity with the JavaScript programming language.
Some familiarity with arrow functions.
Some familiarity with prototypes in JavaScript.

Discussion #

Arrays in JavaScript are list-like objects whose prototype has methods to perform traversal and mutation operations. There are countless use cases in Web Development where arrays will be useful.

The Array.prototype.filter() method creates a new filtered array containing all of the elements in the array that pass the test implemented by the provider function. This provider function can be an arrow function taking an element of the array as input and a boolean pass/fail as output. To clarify, if the output is true the element will be included in the new filtered array. As with most methods in JavaScript, there is considerable flexibility in how they are implemented. For example, instead of an arrow function, the filter method can also take a callback function that returns true or false.

Below is a typical example of how the filter function is used:

var arr1 = [1,2,3,4],
arr2 = [2,4],
res = arr1.filter(item => !arr2.includes(item));


When this program is executed, the result should be [1,3]. That is, for each of the elements in arr1, the provider function is going to check whether the array [2,4] includes that item. If the element is neither 2 nor 4, it will be added to the filtered array.

References #

  1. Array.prototype.filter() - JavaScript | MDN. Assessed 11-21-2021.
  2. Array - JavaScript | MDN. Assessed 11-21-2021.

Share Article