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"]
Copy after login
Copy after login

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"]
Copy after login
Copy after login

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"]
Copy after login

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"]
Copy after login

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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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 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)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles