JavaScript has many array methods on ES6, each with unique uses and benefits.

When developing applications, array methods are mostly used to get a specific list of values and to get one or more matches.

Before listing the differences between the two methods, let’s take a look at each one.

JavaScript the find () method

The 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.

grammar

Arrow functions used in the following syntax.

find((element) => { /* ... */ } ) find((element, index) => { /* ... */ } ) find((element, index, array) => { /* ... * /})Copy the code

We have a list of user objects with the name age and id attributes as follows:

let users = [{
    id:1,
    name: 'John',
    age: 22
}, {
    id:2,
    name: 'Tom',
    age: 22
}, {
    id:3,
    name: 'Balaji',
    age: 24
}];
Copy the code

The following code uses the find() method to find the first user older than 23.

console.log(users.find(user => user.age > 23));
//console
//{ id: 3, name: 'Balaji', age:24}
Copy the code

Now we’re going to find our first user who’s 22 years old

console.log(users.find(user => user.age === 22));
//console
//{ id: 1, name: 'John', age:22}
Copy the code

Assuming no match is found means it returns undefined

console.log(users.find(user => user.age === 25));
//console
//undefined
Copy the code

JavaScript filter () method

The filter() method creates a new array containing all the elements that pass the test function. If no element satisfies the test function, an empty array is returned.

grammar

filter((element) => { /* ... */ } ) filter((element, index) => { /* ... */ } ) filter((element, index, array) => { /* ... * /})Copy the code

We will use the same user array and test function as the filter example.

The following code uses the filter() method to find the first user older than 23.

console.log(users.filter(user => user.age > 23)); [{id: 3, name: 'Balaji', age:24}]Copy the code

Now we’re filtering users who are 22 years old

console.log(users.filter(user => user.age === 22));
//console
//[{ id: 1, name: 'John', age:22},{ id: 2, name: 'Tom', age:22}]
Copy the code

Assuming no match is found means it returns an empty array

console.log(users.filter(user => user.age === 25));
//console
//[]
Copy the code

The difference between find() and filter() is common

concurrent

Higher-order functions: Both of these functions are higher-order functions.

The difference between

1. Pass a test feature

Find () returns the first element.

Filter () returns a new array containing all the elements that pass the test function.

2. If no value satisfies the test function

Find () returns undefined;

Filter () returns an empty array;

\

– End –