Home  >  Article  >  Web Front-end  >  How to use es6 filter()

How to use es6 filter()

青灯夜游
青灯夜游Original
2022-10-11 17:29:374496browse

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