Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between find and filter

Tags:

jquery

I have recently jumped into the world of jQuery. I saw the methods find() and filter() but can not figure out the difference between the two.

What exactly is the difference between the two?

like image 536
Sarfraz Avatar asked Mar 13 '10 12:03

Sarfraz


People also ask

Which is faster filter or find?

find() here will be faster as your filter() method relies on find() anyway.

How do you use Find and filter in JavaScript?

Find and FilterThe find() method returns the first value that matches from the collection. Once it matches the value in findings, it will not check the remaining values in the array collection. The filter() method returns the matched values in an array from the collection.

What is the difference between filter and map in JavaScript?

map creates a new array by transforming every element in an array individually. filter creates a new array by removing elements that don't belong.

What is find in JavaScript?

JavaScript Array find() The find() method returns the value of the first element that passes a test. The find() method executes a function for each array element. The find() method returns undefined if no elements are found. The find() method does not execute the function for empty elements.


1 Answers

Find vs Filter

Let's say you have this array:

var folks = [    {name: "Bob", age: "32", occupation: "developer"},    {name: "Bill", age: "17", occupation: "delinquent"},    {name: "Brad", age: "40", occupation: "yes"}  ] 

Find:

folks.find( fella => fella.name === "Bob") //Returns an object: {name: "Bob", age: "32", occupation: "developer"} 

Filter:

folks.filter( fella => fella.name === "Bob") //Returns an array: [ {name: "Bob", age: "32", occupation: "developer"} ] 
like image 181
daCoda Avatar answered Oct 20 '22 00:10

daCoda