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.
filter reduces the set of already matched elements, while find gets descendants of the matched element.
.find() will look and stop after the first match, whereas, .filter() will continue searching through the entire array
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.
filter gives the array and the data found but find only gives the data in array not the array
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
}];
Find vs Filter
Let's say you have this array:
array folks = [
{name: "Bob", age: "32", occupation: "developer"},
{name: "Bill", age: "17", occupation: "delinquent"},
{name: "Brad", age: "40", occupation: "yes"}
]
Find:
folks.find( fella => name === "Bob")
//Returns an object: {name: "Bob", age: "32", occupation: "developer"}
Filter:
folks.filter( fella => name === "Bob")
//Returns an array: [ {name: "Bob", age: "32", occupation: "developer"} ]