Difference between find and filter

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"} ]

filter reduces the set of already matched elements, while find gets descendants of the matched element.


While looking for answers to the question, I found a nice blog explaining the same.
Mkyong writes:

Both filter() and find() methods are very similar, except the former is applies to all the elements, while latter searches child elements only.

  • filter() – search through all the elements.
  • find() – search through all the child elements only.

Try his demo:

$(document).ready(function() {
  $("#filterClick").click(function() {
    $('div').css('background', 'white');
    $('div').filter('#Fruits').css('background', 'red');
  });

  $("#findClick").click(function() {
    $('div').css('background', 'white');
    $('div').find('#Fruits').css('background', 'red');
  });
});
div {
  padding: 8px;
  border: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

<h1>jQuery find() vs filter() example</h1>
<div id="Fruits">
  Fruits
  <div id="Apple">Apple</div>
  <div id="Banana">Banana</div>
</div>
<div id="Category">
  Category
  <div id="Fruits">Fruits</div>
  <div id="Animals">Animals</div>
</div>
<br/><br/><br/>
<input type='button' value='filter(Fruits)' id='filterClick'>
<input type='button' value='find(Fruits)' id='findClick'>

View on jsFiddle


.find() will look and stop after the first match, whereas, .filter() will continue searching through the entire array

Tags:

Jquery