Home >Web Front-end >JS Tutorial >The difference between find and filter in js
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
undefined
is returned. <code class="javascript">const element = arr.find(callback);</code>
filter
<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!