Convert array.filter()[0] to array.find()pro

Replace anArray.filter(…)[0] with anArray.find(…).

Convert array.filter()[0] to array.find()

Array.find(…) was introduced in ES2015 (ES6). It returns the first element of an array for which the testing function parameter returns a truthy value.

Before the introduction of array.find(…), it was common to use the first element from a filtered result instead, i.e., array.filter(…)[0]. This refactoring modernizes the older expression.

Why is this refactoring helpful?

Array.find(…) is more concise and meaningful, and it avoids allocating a temporary array.

If you are using TypeScript without checked index access (--noUncheckedIndexedAccess), switching to .find will help you identify and handle edge cases where the array does not contain a matching element and .find returns undefined.

What do I need to consider?

Target object might not be an array

.filter can be called on any object that has a filter method. When the object does not provide a find method, and both find and filter have similar semantics to the standard JavaScript array, this refactoring can change the behavior of your code.

Adds 'undefined' to type

If you are using TypeScript without checked index access (--noUncheckedIndexedAccess), then this refactoring changes the return type of the expression. For the array access [0], TypeScript assumes that the element exists (even though it could be undefined). However, when switching to .find, undefined is part of the return type. This can help you uncover potential bugs.

Configuration

Related Code Assists

Learn More

Available In