How to use es6 filter()
In es6, filter() is an array filtering method. It will call a callback function to filter the elements in the array and return all elements that meet the conditions. The syntax "Array.filter(callback(element[, index [, array]])[, thisArg])". The filter() method creates a new array, and the elements in the new array are checked for all elements in the specified array that meet the conditions.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
The array filter method is one of the most widely used methods in JavaScript.
It allows us to quickly filter out elements in an array with specific conditions.
So, in this article, you will learn everything about filter methods and their various use cases.
So let’s get started.
Look at the code below without using the filter method:
const employees = [ { name: 'David Carlson', age: 30 }, { name: 'John Cena', age: 34 }, { name: 'Mike Sheridan', age: 25 }, { name: 'John Carte', age: 50 } ]; const filtered = []; for(let i = 0; i -1) { filtered.push(employees[i]); } } console.log(filtered); // [ { name: "John Cena", age: 34 }, { name: "John Carte", age: 50 }]
In the above code, we are looking for items with John
We are using the indexOf
method to name all employees. The
for loop code looks complicated because we need to manually loop through the employees
array and push matching employees into the filtered
array.
But using the array filtering method, we can simplify the above code.
Array filtering method filter()
filter() method creates a new array. The elements in the new array are determined by checking all elements in the specified array that meet the conditions. .
The syntax of the array filter method is as follows:
Array.filter(callback(element[, index[, array]])[, thisArg])
The filter method does not change the original array, but returns a new array containing all elements that satisfy the provided test condition.
The filter method takes a callback function as the first parameter and executes the callback function for each element of the array.
In each iteration of the callback function, each array element value is passed to the callback function as the first parameter.
Look at the following code using the filter method:
const employees = [ { name: 'David Carlson', age: 30 }, { name: 'John Cena', age: 34 }, { name: 'Mike Sheridan', age: 25 }, { name: 'John Carte', age: 50 } ]; const filtered = employees.filter(function (employee) { return employee.name.indexOf('John') > -1; }); console.log(filtered); // [ { name: "John Cena", age: 34 }, { name: "John Carte", age: 50 }]
Here, using the array filter method, we don’t need to manually loop through employees
Array, there is no need to filtered
create an array in advance to filter out matching employees.
Understand the filter method filter()
The filter method accepts a callback function, and each element of the array is automatically used as the first parameter in each iteration of the loop. transfer.
Suppose we have the following array of numbers:
const numbers = [10, 40, 30, 25, 50, 70];
And we want to find all elements greater than 30, then we can use the filtering method as shown below:
const numbers = [10, 40, 30, 25, 50, 70]; const filtered = numbers.filter(function(number) { return number > 30; }); console.log(filtered); // [40, 50, 70]
So inside the callback function, on the first iteration of the loop, the first element value 10 in the array will be passed as the number
parameter value, and 10> 30 is false, so the number 10 is not considered a match.
The array filter method returns an array, so 10 is not greater than 30, it will not be added to the filtered
array list.
Then on the next iteration of the loop, the next element in the array, 40, will be passed to the callback function as the number
parameter value, which will be considered when 40 > 30 is true as matched and added to the filtered
batch.
This will continue until all elements in the array have not completed the loop.
Therefore, as long as the callback function returns a
false
value, the element will not be added to the filtered array. The filter method returns an array containing only those elements for which the callback function returns atrue
value.
You can see the current value of the element passed to the callback function on each iteration of the loop if you log the value to the console:
const numbers = [10, 40, 30, 25, 50, 70]; const filtered = numbers.filter(function(number) { console.log(number, number > 30); return number > 30; }); console.log(filtered); // [40, 50, 70] /* output 10 false 40 true 30 false 25 false 50 true 70 true [40, 50, 70] */
Now, look at the following code:
const checkedState = [true, false, false, true, true]; const onlyTrueValues = checkedState.filter(function(value) { return value === true; }); console.log(onlyTrueValues); // [true, true, true]
In the above code, we only find out those values that are true
.
回调函数可以如上所示编写,也可以使用箭头函数如下所示:
const onlyTrueValues = checkedState.filter(value => { return value === true; });
而如果箭头函数中只有一条语句,我们可以跳过return关键字,隐式返回值,如下:
const onlyTrueValues = checkedState.filter(value => value === true);
上面的代码可以进一步简化为:
const onlyTrueValues = checkedState.filter(Boolean);
要了解它是如何工作的,请查看我的这篇文章。
回调函数参数
除了数组的实际元素外,传递给 filter 方法的回调函数还接收以下参数:
- 我们正在循环的
index
数组中当前元素的 -
array
我们循环播放的原版
看看下面的代码:
const checkedState = [true, false, false, true, true]; checkedState.filter(function(value, index, array) { console.log(value, index, array); return value === true; }); /* output true 0 [true, false, false, true, true] false 1 [true, false, false, true, true] false 2 [true, false, false, true, true] true 3 [true, false, false, true, true] true 4 [true, false, false, true, true] */
过滤方法的用例
正如您在上面看到的,数组过滤器方法对于过滤掉数组中的数据很有用。
但是过滤器方法在一些实际用例中也很有用,例如从数组中删除重复项,分离两个数组之间的公共元素等。
从数组中删除元素
filter 方法最常见的用例是从数组中删除特定元素。
const users = [ {name: 'David', age: 35}, {name: 'Mike', age: 30}, {name: 'John', age: 28}, {name: 'Tim', age: 48} ]; const userToRemove = 'John'; const updatedUsers = users.filter(user => user.name !== userToRemove); console.log(updatedUsers); /* output [ {name: 'David', age: 35}, {name: 'Mike', age: 30}, {name: 'Tim', age: 48} ] */
在这里,我们从users
名称为 的数组中删除用户John
。
userToRemove
因此,在回调函数中,我们正在检查保留名称与存储在变量中的名称不匹配的用户的条件。
从数组中查找唯一或重复项
const numbers = [10, 20, 10, 30, 10, 30, 50, 70]; const unique = numbers.filter((value, index, array) => { return array.indexOf(value) === index; }) console.log(unique); // [10, 20, 30, 50, 70] const duplicates = numbers.filter((value, index, array) => { return array.indexOf(value) !== index; }) console.log(duplicates); // [10, 10, 30]
该indexOf
方法返回第一个匹配元素的索引,因此,在上面的代码中,我们正在检查我们正在循环的元素的当前索引是否与第一个匹配元素的索引匹配,以找出唯一和重复元素.
查找两个数组之间的不同值
const products1 = ["books","shoes","t-shirt","mobile","jackets"]; const products2 = ["t-shirt", "mobile"]; const filteredProducts = products1.filter(product => products2.indexOf(product) === -1); console.log(filteredProducts); // ["books", "shoes", "jackets"]
在这里,我们products1
使用 filter 方法循环,在回调函数中,我们正在检查products2
数组是否包含我们使用 arrayindexOf
方法循环的当前元素。
如果该元素不匹配,则条件为真,该元素将被添加到filteredProducts
数组中。
您还可以使用数组includes
方法来实现相同的功能:
const products1 = ["books","shoes","t-shirt","mobile","jackets"]; const products2 = ["t-shirt", "mobile"]; const filteredProducts = products1.filter(product => !products2.includes(product)); console.log(filteredProducts); // ["books", "shoes", "jackets"]
浏览器对过滤方法的支持
- 所有现代浏览器和 Internet Explorer (IE) 版本 9 及更高版本
- Microsoft Edge 版本 12 及更高版本
【相关推荐:web前端开发】
The above is the detailed content of How to use es6 filter(). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
