6.13 Filtering an Array
In this video, I'll show you how to filter an array based on search criteria. So let's go back to our array of numbers, let's say you only want to return positive numbers. So we can use the filter method, like this numbers.Filter(). Again, we need to pass a call back function, this function has three parameters, value, index and array. So, of these, we only care about the value, we don't care about the index because I just want to see if the number or the value is positive. So, function value Now we can write a simple expression like this, if the value is greater than or equal to 0. So when we call the filter method, this method loops through this array and executes this call back function for each element. Now if the element matches this criterion, it will add that element to a new array, and finally we can get the new array here. So we'll call const filter. Let's take a look at the result, console log of filtered, so in our filtered array, we only have 1, 2 and 3. Earlier in this section, you saw arrow functions, so this is a good case where you would use an arrow function. You have a single line of code, in this function, and we just return a value. So we get rid of the function keyword, we put an arrow between the parameter and the body of this function. We don't need the parentheses because we only have one parameter, and because we're just returning a value, we can also exclude the return keyword, as well as the braces, and then put everything on the same line like this. Now, we can shorten this code a little bit more, so in this case, we can use an abbreviation like v for value or n for number. Because obviously we're working with this array of numbers. We filter it and we get numbers that are greater than or equal to zero. Now, we're dealing with an array of numbers, in a real application you would use an array of objects. For example, here on the "Yelp" website, you can click on this button to search only for restaurants that are open now. So this is a type of filtering. So if you wanted to implement something like that, instead of an array of numbers, you would have an array of restaurants, and each restaurant has hours of operation so you can filter out the restaurants that are currently open and return them. That's it for filtering an array in JavaScript, we'll see you in a very next video.