Author: Mensah Alkebu-Lan
Table of Contents
Prerequisites
Discussion
References
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));
console.log(res);
When this program is executed, the result should be [1,3]. That is, for each of the elements is 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
- Array.prototype.filter() - JavaScript | MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter. Assessed 11-21-2021.
- Array - JavaScript | MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array. Assessed 11-21-2021.
View original article at https://voices.hassanriver.com/article/2021/11/becoming-javascript-jedi-mastering-javascript-filter/.
Top comments (0)