Home  >  Article  >  Web Front-end  >  The difference between find and filter in js

The difference between find and filter in js

下次还敢
下次还敢Original
2024-05-07 19:21:15684browse

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>

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>

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>

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!

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:Indexof usage in jsNext article:Indexof usage in js