How to use filter() to filter data in Javascript

autoload
Release: 2021-04-15 13:54:03
Original
3785 people have browsed it

How to use filter() to filter data in Javascript

How to filter variables for data types such as arrays and objects? This article mainly usesfilter()to filter a large amount of data to obtain the required data.

1.filter() syntax:

var newArray = arr.filter(callback(element[, index[, array]])[,thisArg])
Copy after login

callback() is a function used to test each element of the array and returns The value that results in true:

  • element: The current element in the array.

  • index: The index of the current element in the array.

  • array: The array itself on which filter was called.

Return value: a filtered array

2. Example:

a. Filter the odd numbers in the array

arr5=[1,2,3,4,5]; res=arr5.filter( (item)=>item %2); console.log(res);
Copy after login

b. Filter the even numbers in the array

arr6=[1,2,3,4,5]; res=arr6.filter( (item)=>!(item %2)); console.log(res);
Copy after login

Recommended: "2021 js interview questions and answers (large summary)

The above is the detailed content of How to use filter() to filter data in Javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!