This post will center around using the `Array.prototype.filter()` function. It's one of the functions in JS I find to be under-appreciated, allowing us to take an array and build a filtered array, using a callback to determine if any given item should be in our new filtered one.
First, let's go over the syntax. It essentially only needs one parameter, the callback used to evaluate each item. That, in turn, takes three parameters, but only one or two are useful. The first is the item we'll be evaluating. The second is the index of the item. The function will need to return a boolean, true for if the item passes our check and should be included in the new array, false if not. Here's an example:
[gist src=https://gist.github.com/benrgreene/9d1c9d078ad7b97a27ad74166900d2fd file=filters.js][/gist]
So, time for a real world example. Let's take an eCommerce site, and more specifically, a collections page. Typically, we'll want filtering on it, say by size.
What we might do is add a `filter-size` data attribute to some checkboxes (each representing a different value). We can grab those values that are checked, and use that to filter our list of products to display. But, how we get those selected values isn't the important thing here, what we do with them after we have them is. Something like this:
[gist src=https://gist.github.com/benrgreene/9d1c9d078ad7b97a27ad74166900d2fd file=store-filters.js][/gist]
Now, some sites will need more complex filter like having both "and" and "or" filtering (say, multiple categories - size, color, style). We can still use the filter method to accomplish this, but it's going to take some extra abstraction. I'll cover that in a future post.