Home >Web Front-end >JS Tutorial >How to use filter() to filter data in Javascript
How to filter variables for data types such as arrays and objects? This article mainly uses filter()
to filter a large amount of data to obtain the required data.
1.filter() syntax:
var newArray = arr.filter(callback(element[, index[, array]])[,thisArg])
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);
b. Filter the even numbers in the array
arr6=[1,2,3,4,5]; res=arr6.filter( (item)=>!(item %2)); console.log(res);
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!