Tutorial: practical application of Array.prototype.find & Array.prototype.findIndex

Need a freelancer (or consultations / help) for a project or want to build a showcase project? Hire me. Expertise: JS, React.js, Redux, Node.js.Click and leave a message or contact@developeryourself.com.
Want to get a Web Developer job having no experience? I provide one-to-one on-line training. Click here.

Here is an explanation with some examples of quite useful ES6 methods that can save you lots of headaches and reduce the amount of code.

Array.prototype.find

This method will return the first element that matches some criteria from the callback function. Otherwise undefined will be returned. Within the callback function we get access to the usual stuff offered by Array.prototype methods i.e.: element, index and the array that we’re checking. As a second argument we can pass some this. Let’s jump into an example:

const predicate = (val, index, array) => {
console.log(val); // 1 ==> 4 ==> 8

return val > 5;
}
const getFirstAbove5Element = [1, 4, 8, 12].find(predicate, undefined);
getFirstAbove5Element; // 8

Easy and straightforward, right? Notice that the undefined is passed explicitly. The second argument is optional and if not provided its value is evaluated to undefined. Let’s pass something else than undefined as the second argument:

const explicitThis = { a: 1, b: 4, c: 8, d: 12 };
function callback(val) {
console.log(this); // {a: 1, b: 4, c: 8, d: 12}
  return val === this.a;
};
const firstMatch = [5].find(callback, explicitThis);
firstMatch; // undefined

The returned value is undefined since the condition was not met (5 !== 1). Notice the use of a ‘normal’ function instead of an arrow counterpart to properly get the this value inside the callback function.

Here’s a useful tip from the docs:

The range of elements processed by find is set before the first call to callbackfn. Elements that are appended to the array after the call to find begins will not be visited by callbackfn. If existing elements of the array are changed, their value as passed to predicate will be the value at the time that find visits them.

Array.prototype.findIndex

Like can be assumed from the name, the index of the element that fulfills the predicate is returned:

const arr = [1, 2, 3];
const getElementIndex = arr.findIndex(val => val === 2);
getElementIndex; // 1
arr[getElementIndex]; // 2

Everything works as expected.

Use case

Combining Array.prototype.find and Array.prototype.findIndex can be useful in cases where we modify some array by updating / moving / deleting / inserting some elements and want to keep the order of the initial array. Consider:

Steps:

  1. Get some element
  2. Get element’s index
  3. Remove the element from array
  4. Modify element’s keys
  5. Bring the element back preserving the original array’s structure

Executing the script will give:

As can be seen, the element at a given initial index (1) was successfully modified.