| by Arround The Web | No comments

filter vs. find: JavaScript Array Methods

In JavaScript, there are various predefined methods used for different operations, such as the “filter()” method, “find()” method, and so on. These two methods are used for performing operations on arrays, such as finding a specific element or a group of elements that matches the specified criteria.

This blog will illustrate the difference between the “filter” and the “find” methods in JavaScript.

filter vs. find in JavaScript

Both the “filter()” method and the “find()” method are used for searching elements in an array based on specific conditions. But there are some differences between them, as follows:

  • The “filter()” method is used to get the subset of data from a large data set based on specific conditions while the “find()” method is utilized to find the specific value/element in data.
  • The “filter()” method gives all the entries or items that match or fulfill the specified test while the “find()” method only gives the first occurrence that matches the specified test.

Let’s understand the working/procedure of these methods with the help of examples.

Example 1: Using the “filter()” Method in JavaScript
Create an array of objects named “arrayObj”:

var arrayObj = [
 {
  id: 1,
  name: "John",
  age: 20
  },
  {
   id: 2,
   name: "Jack",
   age: 22
  },
  {
   id: 3,
   name: "Julian",
   age: 20
  },
]

Call the filter() method and find all the instances of objects in an array whose age is “20”:

var object = arrayObj.filter((obj) => obj.age === 20);

Print the resultant objects on the console:

console.log(object);

As the “filter()” method gives all the occurrences of the specified condition, it will output two objects whose age property has “20” value:

Example 2: Using the “find()” Method in JavaScript
Invoke the “find()” method with the array of objects to locate the objects whose age property is 20. The “find()” method will output the first instance or object whose age is 20:

var object = arrayObj.find((obj) => obj.age === 20);
console.log(object);

Output

That’s all about the filter() vs find() method in JavaScript.

Conclusion

The “filter()” method outputs all the instances of the elements of an array that fulfills the particular criteria while the “find()” method gives only the first instance that matches the given condition. Both of these methods are useful for searching elements in arrays. This blog illustrated the primary difference between the “filter” and the “find” methods in JavaScript.

Share Button

Source: linuxhint.com

Leave a Reply