Home  >  Article  >  Web Front-end  >  How to use filter() to filter data in Javascript

How to use filter() to filter data in Javascript

autoload
autoloadOriginal
2021-04-12 15:06:483841browse

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!

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
Previous article:js what does it meanNext article:js what does it mean