How to use Filter | JavaScript

/ #JavaScript


JavaScript Filter is a Higher-Order function and in this post I'll show you how to use it.

What is a Higher-Order function?

A higher order function is a function that operates on other functions. They can either take functions as arguments, or they can return them. In other words, either you pass inn a function or you get a function in return.

A quick example

Let's say that you have a list of products with a number of quantities in stock. We want to create a new array with all the products with zero in stock. This is how you would solve it without a higher-order function:

const products = [
	{ title: 'Banana', stock: 1 },
	{ title: 'Apple', stock: 3 },
	{ title: 'Orange', stock: 0 },
	{ title: 'Pear', stock: 0 },
	{ title: 'Pineapple', stock: 1 }
];

const outOfStock = [];

for (let i = 0; i < products.length; i++) {
	if (products[i].stock === 0) {
		outOfStock.push(products[i]);
	}
}

// Print the array

console.log(outOfStock);

This is not very elegant. Let's try if using the filter function:

const products = [
	{ title: 'Banana', stock: 1 },
	{ title: 'Apple', stock: 3 },
	{ title: 'Orange', stock: 0 },
	{ title: 'Pear', stock: 0 },
	{ title: 'Pineapple', stock: 1 }
];

const outOfStock = products.filter(product => product.stock === 1);

// Print the array

console.log(outOfStock);

As you can see, solving this using filter is very easy and it looks much better.

Questions?

If any of this was unclear, feel free to leave me a reply below! I'm also open to answer other questions about coding.

Comments

No comments yet...

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.