
Javascript Array Helper: filter
The purpose of the filter() array helper is to execute a function for every array element and return a new array containing only those elements that match a condition.
A Practical Example
Suppose we have an array of products and we want to create a new array of only those products with a category of “books”.
First, let’s look at how we would do this in older ES5 javascript.
</pre> var products = [ { name: 'Checkers', category: 'Toys'}, { name: 'Harry Potter', category: 'Books'}, { name: 'iPhone', category: 'Electronics'}, { name: 'Learn PHP', category: 'Books'} ]; var filteredProducts = []; for (var i=0; i<products.length; i++) { if (products[i].category === 'Books') filteredProducts.push(products[i]); } console.log(filteredProducts); <pre>
Javascript filter() Helper
Here is how the example above would be re-written using the filter helper.
var products = [ { name: 'Checkers', category: 'Toys'}, { name: 'Harry Potter', category: 'Books'}, { name: 'iPhone', category: 'Electronics'}, { name: 'Learn PHP', category: 'Books'} ]; var filteredProducts = []; filteredProducts = products.filter(function(product) { return product.category === 'Books'; }); console.log(filteredProducts);
The way this works is that for each array element, a callback function will get called, where you can test a condition and return true or false.
If you return true then that element will be include in the resulting array. The end results is a brand new array with the elements meeting your condition.
Hope this helps, in my next post I will discuss if the array .find function.