Categories
JavaScript

JavaScript Arrays filter method

After map method we are continuing our series on JavaScript Arrays methods. Today we are going to take a look at filter method. According to MDN: The filter() method creates a new array with all elements that pass the test implemented by the provided function.

What does this mean? It means that you pass criteria to filter method by witch you want to filter out values from initial array, and assign them to new array.

This is pretty useful method and can be used in a lot of cases. Like: return only prices that are higher/lower than price, return all users whose username is larger/smaller than string, or anything like that. Take a look at the example:

Also filter can be used to filter out all the values that are false/falsy, by using Boolean constructor. This is excellent way of handling data.

/**
 * We have an array of values, some of them are falsy, some not. 
 * 
 * We will use filter function to return only truthy ones.
 */ 
let arr = [1, 2, 3, true, false, 'a', 'b', 'c', undefined, null, '', NaN, 4, 5, 6]

let r = arr.filter(Boolean)

console.log(r)
//Output: [1, 2, 3, true, "a", "b", "c", 4, 5, 6]

If you have any questions or anything you can find me on my Twitter, or you can read some of the older articles like console.log in JavaScript – Tips & Tricks