Quantcast
Channel: JavaScript – iAdvise blog
Viewing all articles
Browse latest Browse all 14

5 Minute JavaScript #15: filter

$
0
0

In the previous blogpost we discussed the forEach method that iterates over every array. We can now create a filtered array by using this function.

var filtered = []
arr.forEach(function (item) { if (item.isOkay) filtered.push(item); });

While this will work fine, we still need to predefine our filtered array and push it in this array ourselves. We don’t need to… we could just use the filter method on the array prototype.

var filtered = arr.filter(function (item) { return item.isOkay; });

This code isn’t only more readable and a little shorter, it also allows you to chain these methods. Also, you can use abstract validation functions to reuse the filtering.

var isEven = function (number) { return number % 2 === 0; };
var filtered = [1, 2, 3].filter(isEven);

A more practical example:

var stockItem = { category: "toys" /*, and other properties */ };
var stockItems = [/* has a bunch of stockitems with different categories */];

var product = { category: "toys", stockItems: [] };
var products = [/* has a bunch of products */];

var belongsToToyCategory = function (item) { return item.category === "toys";  };

var filteredStockItems = stockItems.filter(belongsToToyCategory);
var filteredProducts = products.filter(belongsToToyCategory);


Viewing all articles
Browse latest Browse all 14

Latest Images

Trending Articles





Latest Images