The filter function lets you quickly filter data from an array without using a forEach or for loop.
We’ll use the same object as before.
The great thing about filter function is that you can quickly filter your array without using forEach or a standard for loop.
Let’s have a look on how to return stocks with prices higher than 450.00, it’s easy:
The main part of the above is a predicate function (function(stock{…}), a function which returns True or False based on a condition, in this case the condition is ‘stock.price >= 400’. If the result is True, the filter function pushes the ‘current’ stock element (e.g. {symbol:”GG”, price:500.65}) to an array. This Array is then returned by using:
This way we can quickly filter arrays. In the next post I’ll show you how to chain map and filter!