A cool way of getting to know the Higher-Order Function Filter.
Being introduced to Higher-order functions can be very confusing and tricky at first, so let me go over one of the top three Higher-order functions that are used during a coding Bootcamp. If you don’t know already, in JavaScript, a function is a complex data type that can take in a bundle or collection of values with a block code that can return some type of data and are reusable. Since a function is a complex data type, it can take in functions as its arguments or return another function, that's what we call a Higher-order function.
One of the three main Higher-order functions you will be using is the filter function. This filter function does some iterating over an Array, like a for loop or a forEach Higher-order function, to get access to each value or element inside that array. The filter takes a callback function as its arguments that take in every element that is inside the array as its own arguments. A new array is to be returned by the filter function. For whatever elements that pass the test from the callback function will be inside the new Array and the values that do not pass will be filtered out.
Here is a code snippet example of Filter.
Above here, is an Array called users with several objects of people with key-value pairs of their names, the color of their eyes, and age. So let’s say we have all these people on this list, but we only want a list of people with the eye color of blue. This is where we can use the filter function.
Above, you see we have a function called blueEyes and it takes an Array as its argument, which will eventually take in the users Array later on. Inside the function, we are using the filter function on the array parameter, and you can see it has a callback function that uses “user” as its parameter that represents each element inside the Array which is all the objects. Since we have access to the objects, we can use dot notation to get access to the key of “eyeColor”. Without using an if statement, we can simply use a return statement and our strict equal operator to see if the eyeColor is equal to the string of blue. Now we can return the blueUser function that is returning a filter Array with only the elements that have the eye color of blue.
Below, this will be print to the console: only two people with the eye color of blue.