View profile

Essential Array methods in JavaScript. Part 1 - filter

Coderslang Master
Coderslang Master
Hey, there! I hope you’re doing great today and your efforts in becoming a Full Stack JavaScript developer are about to bring some dividends!
I’m about to add a new lecture to the course. It’ll be available only for premium subscribers and I’d like to share some of the content with you.
It’s this lecture, you’ll learn four essential JavaScript methods for working with arrays: forEach, filter, map, and reduce.
Make sure you master those methods before you start applying for a job as it’s a very common topic in the technical interview.
Today, we’ll start with the filter.

How to filter out some array elements in JS
One of the most common data types in JS is an array. All arrays already contain all methods (functions) to work with the data inside the array.
Let’s start with an example of a simple array of a few numbers.
In the line above, I created an array arr. Imagine that you need to create a new array from all the elements of the array arr whose value is greater than zero.
So, let’s create an empty positives array, then iterate over the arr`array with a for loop and put every matching array element in `positives` using the push function.
Not bad, but it could be way better.
The filter function will help you filter out the unwanted elements from the array and return a new array consisting only of suitable items.
To work correctly, the filter function accepts a parameter called “filtering function” or “filtering predicate”.
This “filtering function” takes a single element of the array and returns true if the element passes the filter, otherwise it should return false.
Let’s rewrite the previous example using the filter function.
This is not the shortest option, however. I created the greaterThanZero function just to emphasize that the filter function takes another function as a parameter.
In practice, for simple filters, you will more often see an anonymous filtering function written right inside the parenthesis of a filter.
With filter, you can also work with an array of objects. For example, you might want to filter all users over 18 years of age.
That’s it for now! Next time, I’ll tell you about how you can iterate over an array with the function forEach.
Coderslang: Become a Software Engineer
Don’t miss out on the other issues by Coderslang Master
Did you enjoy this issue? Yes No
Coderslang Master
Coderslang Master @coderslang

Coderslang: Become a Software Engineer

You can manage your subscription here.
In order to unsubscribe, click here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Created with Revue by Twitter.