Skip to Content

Filtering Array Values & Objects with JavaScript

The filter() Array method in JavaScript creates a new array with elements filtered out by passing in criteria to an existing array. This method is especially useful in cases where you're wanting to filter out array items that don't pertain to the functionality you're wanting to accomplish or the result set you're looking for in your application.

Using filter() on an Array of Numbers

Let's say, for example, we have an array of numbers that we need to filter out quickly without writing a bunch of code. Let's consider this example array with five associated numbers:

var numbers = [1, 3, 7, 9, 12];

If we needed to filter out numbers less than 9, for example, we could do so with the following snippet:

var result = numbers.filter(function(item) {
return item > 8;
});

console.log(result);
// output: [9, 12]

When testing this output, you'll see that the result is an array with two nodes, the first equally 9 and the second equalling 12. This is because the filter() method used returned all values within the numbers array that are greater than the numeric value of 8.

Using filter() on an Array of Objects

A more complex but useful solution could be filtering out objects from an array of objects in JavaScript. Let's consider this example:

var foods = [
{
name: "Steak",
type: "Meat"
},
{
name: "Hamburger",
type: "Meat"
},
{
name: "Apple",
type: "Fruit"
},
{
name: "Brocolli",
type: "Vegetable"
}
];

If we wanted to apply a filter() to return all foods with a type that's equal to "Meat", we could do so like this:

var result = foods.filter(function(item) {
return item.type == "Meat";
});

console.log(result);
// output: [{name: "Steak", type: "Meat"},{name: "Hamburger", type: "Meat"}];

Conclusion

As you've now seen, the filter() method in JavaScript can be a powerful tool for filtering out JavaScript Array data to find the information that you need.

Created: January 17, 2022

Comments

There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.