How to efficiently find elements in arrays without needing a boilerplate loop, just using high order functions and callbacks? JavaScript provide us three useful methods: Array#find
, Array#findIndex
and Array#indexOf
.
Finding
Both find
and findIndex
works the same except that find
returns the element and findIndex
returns it’s index. Which one suits you best depends on the case. Both functions have the same callback signature:
- Current item value.
- Current item index.
- The array being looped on.
It’s important you to know that both methods return as soon as they find a match.
In the above case as soon as it find the five at index 2 the loop ends and the rest of the array is ignored.
If they don’t find a match, -1
will be returned.
Although Array#findIndex
looks more promising, there are usages for Array#find
.
Index Of
If you ever find yourself writing code like this:
You realize you where making stupidly simple functions to find a value which seems like just another boilerplate in our life. Happily we have a findIndex
counterpart that looks exactly for a value, Array#indexOf
.
Review
- Use
Array#find
andArray#findIndex
to find items on arrays without the need of a boilerplate loop. - Use
Array#indexOf
if you know the value but you don’t know the index. - If you know the index and want to know the value just use
array[index]
, it’s basic JavaScript.