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?
find() here will be faster as your filter() method relies on find() anyway.
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.
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.
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.
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"} ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With