search
HomeWeb Front-endFront-end Q&AHow to use es6 filter()

How to use es6 filter()

Oct 11, 2022 pm 05:29 PM
javascriptes6es6 array

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.

How to use es6 filter()

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 }]

How to use es6 filter()

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 }]

How to use es6 filter()

Here, using the array filter method, we don’t need to manually loop through employeesArray, 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]

How to use es6 filter()

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 filteredarray 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 a true 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]
*/

How to use es6 filter()

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]

How to use es6 filter()

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]

*/

How to use es6 filter()

过滤方法的用例

正如您在上面看到的,数组过滤器方法对于过滤掉数组中的数据很有用。

但是过滤器方法在一些实际用例中也很有用,例如从数组中删除重复项,分离两个数组之间的公共元素等。

从数组中删除元素

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}
]

*/

How to use es6 filter()

在这里,我们从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]

How to use es6 filter()

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"]

How to use es6 filter()

在这里,我们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"]

How to use es6 filter()

浏览器对过滤方法的支持

  • 所有现代浏览器和 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!

Statement
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
HTML and React's Integration: A Practical GuideHTML and React's Integration: A Practical GuideApr 21, 2025 am 12:16 AM

HTML and React can be seamlessly integrated through JSX to build an efficient user interface. 1) Embed HTML elements using JSX, 2) Optimize rendering performance using virtual DOM, 3) Manage and render HTML structures through componentization. This integration method is not only intuitive, but also improves application performance.

React and HTML: Rendering Data and Handling EventsReact and HTML: Rendering Data and Handling EventsApr 20, 2025 am 12:21 AM

React efficiently renders data through state and props, and handles user events through the synthesis event system. 1) Use useState to manage state, such as the counter example. 2) Event processing is implemented by adding functions in JSX, such as button clicks. 3) The key attribute is required to render the list, such as the TodoList component. 4) For form processing, useState and e.preventDefault(), such as Form components.

The Backend Connection: How React Interacts with ServersThe Backend Connection: How React Interacts with ServersApr 20, 2025 am 12:19 AM

React interacts with the server through HTTP requests to obtain, send, update and delete data. 1) User operation triggers events, 2) Initiate HTTP requests, 3) Process server responses, 4) Update component status and re-render.

React: Focusing on the User Interface (Frontend)React: Focusing on the User Interface (Frontend)Apr 20, 2025 am 12:18 AM

React is a JavaScript library for building user interfaces that improves efficiency through component development and virtual DOM. 1. Components and JSX: Use JSX syntax to define components to enhance code intuitiveness and quality. 2. Virtual DOM and Rendering: Optimize rendering performance through virtual DOM and diff algorithms. 3. State management and Hooks: Hooks such as useState and useEffect simplify state management and side effects handling. 4. Example of usage: From basic forms to advanced global state management, use the ContextAPI. 5. Common errors and debugging: Avoid improper state management and component update problems, and use ReactDevTools to debug. 6. Performance optimization and optimality

React's Role: Frontend or Backend? Clarifying the DistinctionReact's Role: Frontend or Backend? Clarifying the DistinctionApr 20, 2025 am 12:15 AM

Reactisafrontendlibrary,focusedonbuildinguserinterfaces.ItmanagesUIstateandupdatesefficientlyusingavirtualDOM,andinteractswithbackendservicesviaAPIsfordatahandling,butdoesnotprocessorstoredataitself.

React in the HTML: Building Interactive User InterfacesReact in the HTML: Building Interactive User InterfacesApr 20, 2025 am 12:05 AM

React can be embedded in HTML to enhance or completely rewrite traditional HTML pages. 1) The basic steps to using React include adding a root div in HTML and rendering the React component via ReactDOM.render(). 2) More advanced applications include using useState to manage state and implement complex UI interactions such as counters and to-do lists. 3) Optimization and best practices include code segmentation, lazy loading and using React.memo and useMemo to improve performance. Through these methods, developers can leverage the power of React to build dynamic and responsive user interfaces.

React: The Foundation for Modern Frontend DevelopmentReact: The Foundation for Modern Frontend DevelopmentApr 19, 2025 am 12:23 AM

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

The Future of React: Trends and Innovations in Web DevelopmentThe Future of React: Trends and Innovations in Web DevelopmentApr 19, 2025 am 12:22 AM

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.