Many of us are accustomed to using to two common functions in js, that is, filter() and find(). A lot of the times we use these functions without paying a lot attention to it. Let's discuss in which situations should you actually use them.
find():
find is a function that iterates through an array and returns the first element in the array that matches the given predicate.
eg. find the person with name Amy
filter():
filter is a function that iterates through an array and returns a new array of all elements in the array that matches the given predicate.
eg. finding all person whose name's start with 'R'
Now, that we have seen what these two functions essentially do let's see when should we use them.
filter() basically runs through the entire array to see if the given predicate is matched which means you should be only using it if you expect more than one item to match this predicate. Although, this seems like a pretty simple thing to remember a lot of the times we see people using filter in place of find().
When you want to search for an element in the array use find() instead of returning an array from filter and doing something like resultOfFilter[0]
.
The main advantage of using find() in those cases is that find returns as soon as a match is found, but filter would run through the entire array even if a match is found in the 1 st index position
and you don't want to do that for large arrays when all you are concerned about is one match!
See below how filter iterates through all the elements while find returns on the first match.
Top comments (4)
I also often see people do
filter().length
orfind() != null
when really.some()
and .every()` do a better jobHi khush, welcome to Dev.to, and thanks for this post!
It's true, sometimes I use
filter
and then realise later that I'm only looking for one item and should usefind
instead!if you don't care about result then you can use .includes() also :)
I love to learn new find() vs filter() technologies in all platform, but mostly I concentrate on SharePoint and the integration part. Spell to bring him back