Difference between find and filter
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 b开发者_StackOverflow中文版etween the two?
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"} ]
.find() will look and stop after the first match, whereas, .filter() will continue searching through the entire array
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()
find()
returns the descendants of the selected elements that match the selector.
From the doc:
Description: Get the descendants of each element in the current set of matched elements, filtered by a selector.
filter()
filter()
filters the elements based on the selector or the provided function.
From the doc:
Description: Reduce the set of matched elements to those that match the selector or pass the function's test.
Consider you have an array of objects with duplicate values for the 'id' and see below the result for the find and filter methods.
let arrObj = [ { id:1, name:"One" },
{ id:2, name:"Two" },
{ id:1, name:"One" }
];
var resultObj = arrObj.find(v => v.id === 1); // { id: 1, name: 'One'}
var resultArrObj = arrObj.filter(v => v.id === 1); // [
// { id:1, name:"One" },
// { id:1, name:"One" }
// ]
find
:
Stops further iteration once the condition is true.
return 'undefined' if nothing is matched
filter
:
Iterate all the items in the array.
Always return an array.
find()
returns children of the match elements for the given selector, filter()
looks at the matched elements and returns the ones that also match the given selector.
find()
and filter()
both methods work with array
let customers = [{
name: 'ABC Inc',
credit: 100
}, {
name: 'ACME Corp',
credit: 200
}, {
name: 'IoT AG',
credit: 300
}];
What is find()
?
find()
method return the first value which match from the collection. find()
method search the array from the start if the desired value is matched then find()
method return that value and terminate and rest of the array is not process.
let findCustomers = customers.find(customer=>{
return customer.credit<300
})
console.log(findCustomers)
/// [{
name: 'ABC Inc',
credit: 100
}];
What is filter()
?
filter()
method returns the match value from the array. it search whole array from start to end and returns all the value which is matched.
let findCustomers = customers.flter(customer=>{
return customer.credit<300
})
console.log(findCustomers)
/// [{
name: 'ABC Inc',
credit: 100
}, {
name: 'ACME Corp',
credit: 200
}];
filter gives the array and the data found but find only gives the data in array not the array
The filter() method is used to filters all the elements and returns the element that matches and the element that do not match are removed.
The only difference is the filter() method search through all the elements while find() method search through all the child elements only.
find:
- return first item with matching condition
- return an object or value
- return undefined if nothing matched
filter:
- return all matching items
- return an array (always)
- return blank array e.g. [], if nothing matched
Let's see some examples:
const array1 = [5, 12, 8, 130, 44];
**// find**
const found = array1.find(x => x > 10);
// Return 12
**//filter**
const found = array1.filter(element => element > 10);
// Return [12, 130, 44]
Let's see some example of object array:
let person = [
{ name: "Bob", age: "32", occupation: "developer" },
{ name: "Bill", age: "17", occupation: "delinquent" },
{ name: "Brad", age: "40", occupation: "yes" }
];
const found = person.find(item => item.age > 30);
// return { name: "Bob", age: "32", occupation: "developer" }
const found = person.filter(item => item.age > 30);
/* return [
{ name: "Bob", age: "32", occupation: "developer" },
{ name: "Brad", age: "40", occupation: "yes" }
] */
Difference between find and filter
- filter() method search through all the elements.
- find() method search through all the child elements only.
This is more a javascript question then jQuery.
find: returns underfined if not found otherwise returns the found element.
filter: will always return an array that contains the found elements or an empty array.
both functions find and filter can be used to find through all child elements.
精彩评论