Javascript Arrays: find() vs Array findIndex and polyfills
2 min readFeb 22, 2021
Array methods to search for a particular element and its polyfills
Array.prototype.findIndex(predictFn):
- it takes predict function as an argument and returns the index of the first element found and -1 if the element is not found.
let a = [1,2,3,"4",4]
a.findIndex((d) => d == 4) // returns 3
a.find((d) => d === "2") // returns -1
Array.prototype.find(predictFn)
- it behaves exactly the same as above just that it returns the element’s value if found and undefined when it can’t find the element
let a = [1,2,3,"4",4]
a.find((d) => d == 4) // returns "4"
a.find((d) => d === "3") // returns undefined
polyfill for find
if you look closely at the above two functions they’re quite similar to Array.filter
except
- it returns just one value either index or an element and an empty array for the null case
Array.prototype.find = function(predictFn) {
const arr = this; //captures the array
const result = arr.filter(predictFn) //returning a first value
return result.length == 0 ? undefined : result[0]
}
above is a polyfill for find
similar way you can write polyfill for findIndex
too.
there are other functions available in the similar zone for eg indexOf
and includes
you can read about them here: https://hiraljs.medium.com/indexof-vs-includes-30ce7a356360
I find includes
cleaner when it comes to usage and would not use other functions until I have very strong reasons to use them.