Vocabulary of JavaScript: Object-oriented, imperative and functional programming
The power of JavaScript is its versatility, which supports object-oriented programming, imperative programming, and functional programming. Developers can flexibly switch programming paradigms according to project needs and team preferences.
ES5 introduces native array methods such as map
, reduce
and filter
, which greatly facilitates functional programming. Among them, the filter
method can iterate through each element in the array and determine whether to add it to the new array based on the specified test conditions.
Simplify the code using filter
Method
filter
Method makes the code more concise and clear. It iterates over each element in the array and applies the test function. If the test function returns true
, the element will be included in the new array returned by the filter
method.
filter
method works in conjunction with the other two functional array methods of ES5, map
and reduce
, and can be used in combination to create concise and efficient code while keeping the original array unchanged.
While the filter
method may be slightly slower than the for
loop, its code simplicity and maintainability advantages make it a recommended practice. With the optimization of the JavaScript engine, its performance is expected to be further improved.
This article was reviewed by Dan Prince, Vildan Softic and Joan Yinn. Thanks to all SitePoint peer reviewers for getting SitePoint content to its best!
One of the reasons I like JavaScript is its flexibility. It allows you to use object-oriented programming, imperative programming, and even functional programming, and can switch between them based on your current needs and team preferences and expectations.
While JavaScript supports functional technology, it is not optimized for pure functional programming like Haskell or Scala. While I don't usually build my JavaScript programs into 100% functional, I like to use the concept of functional programming to help me keep my code simplicity and focus on designing code that is easy to reuse and test.
Filter dataset using filter
method
The emergence of ES5 makes JavaScript arrays inherit some methods that make functional programming more convenient. JavaScript arrays can now be mapped, regulated, and filtered natively. Each method traverses every item in the array, performs analysis without looping or local state changes, returning results that can be used immediately or operated further. In this article, I want to introduce you to filtering. Filtering allows you to evaluate each item of the array and determine whether to return a new array containing the element based on the test conditions you passed in. When you use Array's filter method, you'll get another array that is the same length as the original array or shorter, containing subset items in the original array that matches the conditions you set.
Filter using loop demonstration
An example of a simple problem that may benefit from filtering is to limit arrays of strings to strings with only three characters. This is not a complicated problem, we can easily solve it using normal JavaScript for loops and without using filter methods. It might look like this:
var animals = ["cat","dog","fish"]; var threeLetterAnimals = []; for (let count = 0; count < animals.length; count++) { if (animals[count].length === 3) { threeLetterAnimals.push(animals[count]); } } console.log(threeLetterAnimals); // ["cat", "dog"]
What we do here is define an array containing three strings and create an empty array where we can store only three characters of string. We define a count variable that is used in a for loop when iterating through the array. Every time we encounter a string that happens to have three characters, we push it into our new empty array. Once done, we just need to record the results. Nothing prevents us from modifying the original array in a loop, but doing so will permanently lose the original value. It's much cleaner to create a new array and keep the original array unchanged.
Using filter
Method
We did not have any technical errors in doing this, but the availability of the filter method on Array allows us to make our code more concise and direct. Here is an example of how to do the exact same thing using the filter method:
var animals = ["cat","dog","fish"]; var threeLetterAnimals = []; for (let count = 0; count < animals.length; count++) { if (animals[count].length === 3) { threeLetterAnimals.push(animals[count]); } } console.log(threeLetterAnimals); // ["cat", "dog"]
As before, we start with the variables containing the original array, and we define a new variable for an array that will contain only strings with three characters. But in this case, when we define the second array, we assign it directly to the result of applying the filter method to the original animals array. We pass an anonymous inline function to filter that returns true only if the value length of its operation is 3. The filter method works by iterating over each element in the array and applying the test function to that element. If the test function returns true for the element, the array returned by the filter method will contain the element. Other elements will be skipped. You can see how concise the code looks. Even if you don't understand the role of filter in advance, you can check this code and figure out its intention. One benefit of functional programming is that it reduces the number of local states to be tracked and limits the modification of external variables from within the function, thereby improving the simplicity of the code. In this case, the count variables and the various states we take when we traversing the original array are just more states that need to be tracked. Using filter, we have managed to eliminate for loops as well as count variables. We don't change the value of a new array as many times as before. We define it only once and assign it the value obtained from applying our filter condition to the original array.
Other ways to format filters
If we use const declarations and anonymous inline arrow functions, our code can be more concise. These are EcmaScript 6 (ES6) features that are natively supported by most browsers and JavaScript engines now.
var animals = ["cat","dog","fish"]; var threeLetterAnimals = animals.filter(function(animal) { return animal.length === 3; }); console.log(threeLetterAnimals); // ["cat", "dog"]
While it is best to go beyond the old syntax in most cases unless you need to match your code to an existing code base, it is important to choose it. As we become more concise, each line of our code becomes more complex. Part of what makes JavaScript so interesting is that you can try to design the same code using many ways to optimize size, efficiency, clarity, or maintainability to suit your team's preferences. But this also puts a greater burden on the team, requiring creating shared style guides and discussing the pros and cons of each choice. In this case, to make our code more readable and versatile, we might want to take the anonymous inline arrow function above and convert it into a traditional named function, and then pass that named function directly to the filter in the method. The code may look like this:
const animals = ["cat","dog","fish"]; const threeLetterAnimals = animals.filter(item => item.length === 3); console.log(threeLetterAnimals); // ["cat", "dog"]
All we do here is extract the anonymous inline arrow function defined above and convert it into a separate named function. As we can see, we have defined a pure function that takes the appropriate value type of the array element and returns the same type. We can directly pass the name of the function as a condition to the filter method.
(Survey content, regarding map
, reduce
and chain calls, please add it according to the original text due to space limitations.) Maintain the original text's pictures and format.
The above is the detailed content of Filtering and Chaining in Functional JavaScript. For more information, please follow other related articles on the PHP Chinese website!