Javascript filter method 4 tips on how to use efficiently

Javascript

The Javascript filter method has a very simple function. It creates, and fills, a new array based on the elements of the array that pass the test you’ve defined (your filter).

1 – Javascript filter method with an arrow function

Arrow functions first appeared in ES6. They’re nothing more that an alternate and more compact way of expressing a regular function.

If the function only has one statement, and it returns a value, you can even remove the curly brackets {} and the return keyword.

const years = [ 1993, 2000, 2015, 2020];
checkYears = years.filter(year => year > 2000);

console.log(checkYears); // [ 2015, 2020 ]

2 – Working with JSON

JSON is an acronym for: JavaScript Object Notation.

JSON’s format is syntactically identical to the object creation in JavaScript.

Because of this, a program written in JavaScript can easily convert JSON data into native JavaScript objects.

And our filter() method can also be used in array with JSON objects, not only simple arrays!

let users = [{ "name": "John", "age": 30, "car": null },
{ "name": "Carlos", "age": 25, "car": "Toyota" },
{ "name": "Brendan", "age": 65, "car": "BMW" },
{ "name": "Carol", "age": 34, "car": "Mercedez" },
{ "name": "Conway", "age": 36, "car": "Mazda" }]


checkUsers = users.filter(user => user.age >= 35);
console.log(checkUsers);
/*
[ { name: 'Brendan', age: 65, car: 'BMW' },
  { name: 'Conway', age: 36, car: 'Mazda' } ]
*/

3 – Chaining the filter method with other methods

Because our Javascript filter method returns a new array, you can chain it’s result with other iterative methods like sort() or map().

You can see it in action down below:

  • First, I’ve used filter(), which returns an array with only users older than 30 years.
  • Second, the sort() method sorts the array by name. (as ascending)
  • Third, our map() function prints out the info .
let users = [{ name: "John", age: 30, car: null },
{ name: "Carlos", age: 25, car: "Toyota" },
{ name: "Brendan", age: 65, car: "BMW" },
{ name: "Carol", age: 34, car: "Mercedez" },
{ name: "Conway", age: 36, car: "Mazda" }]

users
    .filter(user => user.age > 30)
    .sort((c1, c2) => c1.name - c2.name)
    .map(user => console.log(user.name + ': ' + user.car));

/*
Brendan: BMW
Carol: Mercedez
Conway: Mazda
*/

4 – Using this with the filter() method

The keyword this, in Javascript, can be a real nightmare sometimes. However, the filter() method allow us to pass a second argument in it is calling, right after the function’s callback, thisArg.

let newArray = arr.filter(callback(element[, index, [array]])[, thisArg])

If you wish, you can head further deep into the official docs.

This is the value which the keyword this is referring to, when the callback runs.

For instance, I’m passing to filter() my object range, which contains the interval of years that I want to filter from the array.

I’ve also used sort() to organize it’s values.

filterInRange = function (year) {
    if (typeof year !== 'number') {
        return false;
    }
    return year >= this.min && year <= this.max;
}

let years = [1999, 1874, undefined, "2002", 1993, 2015, 'Debug Everything', null, '@'];

let range = {
    min: 1990,
    max: 2010
};

let yearsInRange = years.filter(filterInRange, range).sort((c1, c2) => c1 - c2);

console.log(yearsInRange); // [ 1993, 1999 ]

While using arrow functions, the behaviour of this changes, and that’s why I didn’t use it here. 

In this tutorial, you’ve learned how to use JavaScript’s filter() method to filter elements in an array  based on a test, given by a function callback.

If you wanna see more examples on how to use Javascript filter() method I also have this post with 4 Better Ways to use the Javascript array filter method.

Leave a Reply

Your email address will not be published. Required fields are marked *

0 Comments