Lambda JS #6: Find

Lubien
Lambda JS
Published in
2 min readJun 4, 2019

[Table of Contents] [Previous] [Next]

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:

  1. Current item value.
  2. Current item index.
  3. 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

  1. Use Array#find and Array#findIndex to find items on arrays without the need of a boilerplate loop.
  2. Use Array#indexOf if you know the value but you don’t know the index.
  3. If you know the index and want to know the value just use array[index], it’s basic JavaScript.

Links

--

--

Lubien
Lambda JS

Web developer that loves to make JoJo references