Home >Web Front-end >JS Tutorial >How to use filter in JavaScript
Filter is a method of narrowing the contents of an array under specific conditions. It is used to judge a single element under the conditions specified by the callback function and only retrieve elements that match the conditions. Therefore, let’s take a closer look in this article. See how to use the filter filter in How to use filter in How to use filter in How to use filter in JavaScript.
Let’s first take a look at the basic syntax of filter
When using filter, please specify the filter method of the array.
array.filter(callback [,that]);
For array, you need to specify a pre-created array object.
For callbacks, you can specify the value "value" of the array element, the numeric index "index" of the array element, and the array object "arrayObj" that stores the array element.
For each array element, the elements for which callbak returns true will be generated as a new array, and the elements for which callcak does not return true will be skipped and not included in the new array.
Let’s look at specific examples
The following is an example of extracting specific conditions from an array by actually using the filter method
Extract odd numbers from the array
The code is as follows
##
var data = [1, 4, 7, 12, 21]; var result = data.filter(function(value) { return value % 2 === 1; }); console.log(result);The running results are as follows
Delete numbers less than 5 from the array
The code is as followsvar numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; function isMinNum(value) { return (value >= 5); } var filterNum = numbers.filter(isMinNum); console.log(filterNum);The running result is as follows
Extract the string that matches the condition from the string
The code is as followsvar items = ["item1", "item2", "item3"]; var filterItems = items.filter(function(value) { return value === "item2"; }); console.log(filterItems);The running result is as follows This article ends here. For more exciting content, you can pay attention to the relevant tutorial columns of the php Chinese website! ! !
The above is the detailed content of How to use filter in JavaScript. For more information, please follow other related articles on the PHP Chinese website!