Joe Wayne

I talk about technology, programming and development.

8 Simple Tricks to Filter Arrays Efficiently and Effectively

In this post, I’ll talk about some JavaScript tricks filter()that you need to know. These tricks will help you use the method filter()more efficiently and effectively.

The filter() method is an easy tool to understand, but it can be a bit tricky to use, especially when you want to do more advanced things. These tips I’m going to share will help you avoid some of the most common problems.

Introduction

Want to clean, remove or simply select some specific elements? filter()is your main tool.

Have you ever needed to handle a giant data set using JavaScript? By the way, there are ways to avoid this, such as pagination , but I won’t go into that here, but let’s imagine that you’ve received on the front-end or in some Node.js application, a list or a giant data object that you need to handle.

Maybe filter()is your first option because it creates a new array with elements that pass a specific test defined by a function, this already reduces the amount of data you need to process.

The method filter()receives a callback function as an argument and this function is called for each element of the array. If the callback function returns true, the element is included in the new array, simple as that.

By the way, the original array is not changed.

1. Filter an array using multiple conditions with the method filter()

You can use the method filter()to create a new array that contains only elements that meet multiple conditions. For example, to create a new array that contains only numbers that are even and greater than 5:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 
const numbersEvenGreaterThanFive = numbers.filter(number => number % 2 === 0 && number > 5); 

In the code snippet above, the callback function checks if the number is even and greater than 5. If so, the element is included in the new array  numbersEvenGreaterThanFive.

And here’s the opposite example, filtering the array to include only odd numbers and numbers less than 5:

const oddNumbersGreaterThan5 = numbers.filter(number => number % 2 !== 0 && number < 5); 

You can use the method  filter() to filter arrays with any number of conditions.

2. Filter an array by data type using the methodfilter()

Suppose you have an array with different data types, like this:

const mixedArray = [1, "string", true, {}, [], null];

You can use the method filter()to create a new array that contains only elements of a specific type. For example, to create a new array that contains only strings, you would do the following:

const strings = mixedArray.filter(element => typeof element === "string");

If the element is a string, it will be included in the new array strings(the operator typeofreturns the data type of a value).

You can use the method filter()to filter arrays by any data type, numbers, objects, arrays and even nulland undefined.

And here to filter the array to include only numbers:

const numbers = mixedArray.filter(element => typeof element === "number");

Or just elements that are objects:

const objects = mixedArray.filter(element => typeof element === "object");

3. Filter an array by an object property using the method filter()

Ok, suppose you have an array of objects, like this:

const users = [
  { name: "Alice", age: 25, occupation: "Software Engineer", location: "United States" },
  { name: "Bob", age: 30, occupation: "Business Analyst", location: "Bahamas" },
  { name: "Carol", age: 20, occupation: "Analyst Programmer", location: "London" },
];

You can use the method filter()to create a new array that contains only objects where a specific property has a specific value.

For example, to create a new array that contains only users over the age of 25, you would do the following, using dot notation to access the object’s properties :

const adultUsers = users.filter(user => user.age > 25);

The callback function in this example checks whether the ageobject property usersis greater than 25. If it is, the object is included in the new array adultUsers.

You can use the method filter()to filter objects by any value of any property. For example, you can filter this array by user name, location, or occupation.

Here’s an example of how to filter the array to only include users who live in the United States:

const usUsers = users.filter(user => user.location === "United States");

And here’s an example to only include users who are employed as software engineers:

const softwareEngineerUsers = users.filter(user => user.occupation === "Software Engineer");

4. Filter an array by nested object property using the method filter().

Imagine you have a list of products, like this:

const products = [
  {
    name: "Smart TV",
    categories: ["Electronics", "Home & Garden"],
    isOnSale: true,
  },
  {
    name: "Sunglasses",
    categories: ["Clothing", "Accessories"],
    isOnSale: false,
  },
  {
    name: "Printer",
    categories: ["Electronics", "Office Supplies"],
    isOnSale: true,
  },
];

It looks a little like the previous example, but notice that in this array, categoriesit is also an array, since it makes sense for a product to belong to more than one category.

But that’s okay, we can still use the filter method to filter products from a single category. For example, to filter the array to include only products that are in the “Electronics” category, you would do the following:

const electronicProducts = products.filter(product => product.categories.includes("Electronics"));

The method includes()returns truewhether the array contains the specified value and falseotherwise.

Or, to filter the array to only include products from the “Home & Garden” category:

const homeAndGardenProducts = products.filter(
  product => product.categories.includes("Home & Garden")
);

You can also use the method filter()to filter the array by multiple properties. For example, to filter the array produtosto include only products that are in the “Electronics” category and are also on sale, you would do the following:

const electronicProductsOnSale = products.filter(
  product => product.categories.includes("Electronics") && product.isOnSale
);

5. Filter an array by regular expression using Javascript method filter()

Regular expressions ( regex ) are a powerful tool for filtering arrays by any criteria you want.

You can find specific patterns in strings and you can use this to filter arrays of strings, objects, or any other type of array. To filter an array with a regular expression, you just need to pass a callback function that uses the regex to the method filter().

For example, to find any string that starts with the letter A, you could use the regex /^A/i:

const strings = ["Apple", "Banana", "Cat", "Dog"];

const aStrings = strings.filter(string => string.match(/^A/i));

console.log(aStrings); // ["Apple"]

Here we are using not only the method filter, but also the method string.match()to find the pattern.

Imagine you have a list of email addresses and you want to filter it to only include addresses from a specific domain, like “example.com”. You can use the method filter()combined with regular expressions to do this.

const emailAddresses = ["alice@example.com", "bob@example.com", "carol@gmail.com", "dave@yahoo.com"];

const exampleEmailAddresses = emailAddresses.filter(emailAddress => emailAddress.match(/@example.com$/));

console.log(exampleEmailAddresses); // ["alice@example.com", "bob@example.com"]

The regular expression /@example.com$/matches any string that ends with “@example.com”.

You can use regular expressions to filter arrays by any criteria you want, for example, you could filter an array of email addresses by name, domain, or any other property of the email, or even by whether the format is valid or invalid:

const emailAddresses = ["alice@example.com", "bob@example.com", "carol@gmail.com", "dave@yahoo.com", "invalid_email_address"];

const validEmailAddresses = emailAddresses.filter(emailAddress => emailAddress.match(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/));

console.log(validEmailAddresses); // ["alice@example.com", "bob@example.com", "carol@gmail.com", "dave@yahoo.com"]

6. Filter arrays more efficiently using filter()chained methods

Ok, we’ve seen that it’s possible to filter any array using multiple conditions. Another way to do this is to chain the method filter()to other filters.

When you use a single method filter()with multiple conditions, JavaScript needs to create a new array for each condition, this can be inefficient if you are filtering a large array.

When you use chained methods filter(), JavaScript only needs to create a new array. This is because the output of one method filter()is used as input to the next method filter().

Here is an example:

const products = [
  { name: "Product A", price: 10, category: "electronics" },
  { name: "Product B", price: 20, category: "clothing" },
  { name: "Product C", price: 30, category: "electronics" },
  { name: "Product D", price: 40, category: "clothing" },
];

const cheapElectronicProducts = products.filter(
  product => product.price < 20 && product.category === "electronics"
);

This code first filters the array productsto only include products that cost less than $20 and are in the “electronics” category using both conditions in the same filter().

Now here is the same filter, but using 2 filter()chained methods:

const products = [
  { name: "Product A", price: 10, category: "electronics" },
  { name: "Product B", price: 20, category: "clothing" },
  { name: "Product C", price: 30, category: "electronics" },
  { name: "Product D", price: 40, category: "clothing" },
];

const cheapElectronicProducts = products
  .filter(product => product.price < 20)
  .filter(product => product.category === "electronics");

This code also creates two new arrays, but in a more efficient way. The first method filtercreates a new array of products that cost less than $20. The second method filteruses the output of the first method as input to create a new array of products in the “electronics” category.

Chaining the filter method can be more efficient than using a single one filterwith multiple conditions, especially for large arrays.

7. Filter an array by chaining other methods

Ok, you’ve seen that it is possible to chain two or more methods filter(), what you haven’t seen yet is that you can also chain the method filter()with other methods, like map()and reduce().

For example, the following code chains the filter()and methods map()to get the name of all electronic products:

const products = [
  { name: "Product A", price: 10, category: "electronics" },
  { name: "Product B", price: 20, category: "clothing" },
  { name: "Product C", price: 30, category: "electronics" },
  { name: "Product D", price: 40, category: "clothing" },
];

const cheapElectronicProductNames = products.filter(product => product.price < 20)
  .filter(product => product.category === "electronics")
  .map(product => product.name);

console.log(cheapElectronicProductNames); // ["Product A"]

This code first filters the array productsto include only products that cost less than $20. Then, it filters the array to include only products in the “electronics” category. Finally, it maps the filtered array to a new array containing only the names of all products that cost less than $20.

You can chain the method filter()with any other method that takes an array as input and returns an array as output.

Let’s test with other properties, for example, by price:

const electronicProductPrices = products.filter(product => product.price < 20)
  .filter(product => product.category === "electronics")
  .map(product => product.price);

console.log(electronicProductPrices); // [10]

Or here, we’ll filter by age and location, and then we’ll count the number of users who meet those conditions.

const totalUsersUnder18InCalifornia = users.filter(user => user.age < 18)
  .filter(user => user.location === "California")
  .reduce((total, user) => total + 1, 0);

console.log(totalUsersUnder18InCalifornia); // 10

And to close, let’s filter by price, category and then sort the products by price.

const sortedCheapElectronicProducts = products.filter(product => product.price < 20)
  .filter(product => product.category === "electronics")
  .sort((productA, productB) => productA.price - productB.price);

console.log(sortedCheapElectronicProducts); // [{ name: "Product A", price: 10, category: "electronics" }]

8. Filter unique elements from an array using the methodfilter()

Now lastly, one of the most common examples, imagine you have an array of numbers and you want to filter all the duplicate elements. Using the filter()you will check if the element is already present in the array, if the element is not present, the callback function should return true. Otherwise, the callback function should return false.

Here is an example of how to do this:

const numbers = [1, 2, 3, 1, 4, 5, 2, 6];

const uniqueNumbers = numbers.filter((number, index) => {
  return numbers.indexOf(number) === index;
});

console.log(uniqueNumbers); // [1, 2, 3, 4, 5, 6]

Ok, now a little more complex, let’s try to do the same thing, but now, with an array of objects. For example, let’s say you have an array of users and you want to filter all duplicates based on the “name” property.

You can use the same approach as in the first example, but you will need to modify the callback function to check the “name” property.

Something like this:

const users = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Carol", age: 35 },
  { name: "Alice", age: 20 },
];

const uniqueUsers = users.filter((user, index) => {
  return users.findIndex((otherUser) => otherUser.name === user.name) === index;
});

console.log(uniqueUsers); // [{ name: "Alice", age: 25 }, { name: "Bob", age: 30 }, { name: "Carol", age: 35 }]

Conclusion

From filtering by multiple conditions to creating complex regex patterns, filtering based on value types to focusing on object properties and nested objects, we explored a range of possibilities.

Chaining filters and integrating other methods like map()and reduce()into the mix further expands your array manipulation toolkit.

I believe that you are now better prepared to deal with many of the most common programming problems. But if you have any questions, leave a comment, I’ll see you next time!

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *