Which one has faster results? Consider thousands of record in array so after execution of map, filters, and find function in Javascript
var folks = [
{name: "Nill", age: "20", occupation: "delinquent"},
{name: "John", age: "3", occupation: "delinquent"},
{name: "Bob", age: "32", occupation: "developer"},
{name: "Bill", age: "17", occupation: "delinquent"},
{name: "Bob", age: "40", occupation: "yes"}
]
var i;
const b1=folks.map( fella => {
if(fella.name == "Bob"){
i= fella
}
})
console.log(i)
const a=folks.find( fella => fella.name === "Bob")
console.log(a)
const b=folks.filter( fella => fella.name === "Bob")
console.log(b)
2
Answers
For your question about which one is faster –
map()
,filter()
, orfind()
in JavaScript, the simplest answer isfind()
.Here’s why:
Imagine you’re playing hide and seek. Map would check every hiding spot even if it finds the person you’re looking for right away. Filter goes through every possible spot too, making sure no one is left behind. But find is the quickest. It stops looking as soon as it finds the person. So, if you just need the first match, go with find. It doesn’t waste time and gets you the result fast.
As per your code in this case, finding objects with the name "Bob"),
find()
would generally provide the fastest result amongmap()
,find()
, andfilter()
.Here’s a brief comparison:
1.
map()
: This iterates over each element in the array and applies a function to each element, returning a new array. It’s not optimized for searching or filtering but rather for transforming each element. In your example, it’s not efficient because you’re usingmap()
to iterate over all elements, even though you’re only interested in finding one.2.
find()
: This method stops iterating as soon as it finds the first matching element. It’s ideal for finding a single element in an array that satisfies a condition. It has a complexity of O(n), where n is the number of elements in the array. In your example,find()
would be the best choice for finding the object with the name "Bob".3.
filter()
: This method creates a new array with all elements that pass the test implemented by the provided function. It’s useful when you want to find multiple elements that satisfy a condition. It also has a complexity of O(n), but it may iterate over the entire array even if the first matching element is found early on.Given your code, you can see that
find()
would generally be the fastest for this specific task. However, it’s always a good idea to profile your code in different scenarios and environments to get a more accurate understanding of performance.