国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Web Front-end JS Tutorial Filtering and Chaining in Functional JavaScript

Filtering and Chaining in Functional JavaScript

Feb 17, 2025 am 11:34 AM

Filtering and Chaining in Functional JavaScript

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.

The

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!

Filtering and Chaining in Functional JavaScript

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java vs. JavaScript: Clearing Up the Confusion Java vs. JavaScript: Clearing Up the Confusion Jun 20, 2025 am 12:27 AM

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScript vs. Java: A Comprehensive Comparison for Developers JavaScript vs. Java: A Comprehensive Comparison for Developers Jun 20, 2025 am 12:21 AM

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

JavaScript: Exploring Data Types for Efficient Coding JavaScript: Exploring Data Types for Efficient Coding Jun 20, 2025 am 12:46 AM

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

How can you reduce the payload size of a JavaScript application? How can you reduce the payload size of a JavaScript application? Jun 26, 2025 am 12:54 AM

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

A definitive JS roundup on JavaScript modules: ES Modules vs CommonJS A definitive JS roundup on JavaScript modules: ES Modules vs CommonJS Jul 02, 2025 am 01:28 AM

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.

See all articles