Home >Web Front-end >Front-end Q&A >What is the difference between find and filter in es6
The difference between find and filter in es6: 1. When searching for qualified content in the array without changing the array, the result returned by the find method is an object, and the result returned by the filter method is an array; 2. If no value satisfies the test function, the find method returns undefined, and the filter method returns an empty array.
The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.
1. Find and filter are both methods that do not change the original array. They both find content that meets the conditions in the array without changing the array. , the difference is that find returns an object, and filter returns an array.
The example is as follows:
const list = [{'name':'1',index:1},{'name':'2'},{'name':'1'}] let list2 = list.find(i=>i.name==='1') let list3 = list.filter(i=>i.name==='1') console.log(list); [ { name: '1', index: 1 }, { name: '2' }, { name: '1' } ] console.log(list2); { name: '1', index: 1 } console.log(list3);[ { name: '1', index: 1 }, { name: '1' } ]
find only finds the first result that meets the conditions. In the example, it directly returns an object instead of an array! , and filter returns all results still as arrays.
Note: find() will not traverse the following elements after finding the first element, so if there are two identical elements in the array, it will only find the first one, and the second one will It won’t be traversed again.
2. In summary, find query efficiency is higher, so if the data in the array is unique, it is best to use find
find()
ES6 find() method returns the value of the first element that passes the test function. If no value satisfies the test function, undefined is returned.
Syntax
Arrow functions used in the following syntax.
find((element) => { /* ... */ } ) find((element, index) => { /* ... */ } ) find((element, index, array) => { /* ... */ } )
filter()
The filter() method creates a new array containing all elements that pass the test function. If no elements satisfy the test function, an empty array is returned.
Grammar
filter((element) => { /* ... */ } ) filter((element, index) => { /* ... */ } ) filter((element, index, array) => { /* ... */ } )
Common points
Higher-order functions: Both functions are higher-order functions.
Difference
1. Return the first element through a test function
find().
filter() returns a new array containing all elements that passed the test function.
2. If no value satisfies the test function
find() returns undefined;
filter() returns an empty array;
[Related recommendations :javascript video tutorial、web front-end】
The above is the detailed content of What is the difference between find and filter in es6. For more information, please follow other related articles on the PHP Chinese website!