Home > Web Front-end > JS Tutorial > body text

The difference between find and filter in js

下次还敢
Release: 2024-05-07 19:21:15
Original
689 people have browsed it

The difference between find and filter in JavaScript

find and filter are both functions used for array processing in JavaScript, but they Differences in usage and results.

find

  • Usage: Find the first element in an array that satisfies a given condition.
  • Returns: The first element that meets the condition, if it does not exist, undefined is returned.
  • Syntax:
<code class="javascript">const element = arr.find(callback);</code>
Copy after login

filter

  • Usage: From array Filter out all elements that meet the given conditions and return a new array.
  • Return: An array composed of elements that meet the conditions.
  • Grammar:
<code class="javascript">const newArray = arr.filter(callback);</code>
Copy after login

Summary of differences:

Features find filter
Return value The first element that satisfies the condition Array composed of elements that satisfy the condition
Condition Single condition Any number of conditions
Result Modify the original array Create a new array

##Example:

<code class="javascript">const ages = [20, 25, 30, 35, 40];

// 查找第一个年龄超过 30 的人
const personOver30 = ages.find(age => age > 30); // 35

// 过滤出所有年龄小于 30 的人
const peopleUnder30 = ages.filter(age => age < 30); // [20, 25]</code>
Copy after login

The above is the detailed content of The difference between find and filter in js. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
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!