With the Array filter() method, you provide a function that returns an array containing the “filtered” elements. It is within this function that you provide the logic that determines how your original array is filtered.
Using a for-loop to filter an Array -Example # 1
See the Pen Array.prototype.filter- Challenge by Kevin Chisholm (@kevinchisholm) on CodePen.
Back to Example # 1. Inside of the “while” loop, we use the value of “i” to determine if the current word should be pushed to the “shorter” array or the “longer” array. Once this loop has completed, we update the UI to show the number of “shorter” and “longer” words. Again, perfectly valid code, but kind of verbose and less than optimal.
Using the Array filter() method -Example # 2
See the Pen Array.prototype.filter – Solution # 1 by Kevin Chisholm (@kevinchisholm) on CodePen.
Example # 2 is a major improvement over the previous code. We leverage the Array filter() method to determine the number of “shorter” and “longer” words. There are a couple of areas of improvement here.
First, we’ve removed the need to manually push words to the “shorter” and “longer” arrays, because of the simple syntax of the Array filter() method. Notice that as we create the “shorter” and “longer” arrays, we assign the value by executing the Array filter() method. We provide an anonymous function to the Array filter() method, and the logic is simple: the sole argument passed to that anonymous function is the iterated word, and inside of the function we simply determine if the word’s length is greater than or less than five.
Second, we’ve removed the “while” loop. This is a major improvement, given the fact that it reduces the amount of code, but also since there is no longer any possibility that our code will run forever because of the use of a “while” loop.
Passing a function to the Array filter() method – Example # 3
See the Pen Array.prototype.filter – Solution # 2 by Kevin Chisholm (@kevinchisholm) on CodePen.
The winsPrize() function approach of Example # 3 differs a bit. Instead of using an anonymous function when executing the Array filter() method, we pass a function declaration. Also, we’ve chained the Array filter() method off of an array literal (in other words: we create the array and then immediately execute the filter method). This is not necessarily a “more correct” approach, it’s just less verbose. The logic of the winsPrize() function is similar to the code in Example # 2. The main difference is that we pass a function declaration instead of an anonymous function.