This is an issue when using .filter() followed by array access methods like [0], .at(-1), .shift(), .pop(), or destructuring to get a single element from an array.

Why is this an issue?

Using .filter() to find a single element is inefficient and unclear in intent.

The .filter() method processes the entire array and creates a new array containing all matching elements. When you only need the first or last matching element, this approach has several problems:

The .find() method is specifically designed for finding the first matching element, and .findLast() for finding the last matching element. Both methods:

This pattern is especially problematic in performance-critical code or when working with large arrays, where the unnecessary processing can become a bottleneck.

What is the potential impact?

Using .filter() instead of .find() or .findLast() can lead to unnecessary performance overhead, especially with large arrays. The code also becomes less readable and maintainable, as the intent to find a single element is obscured by the filtering operation.

How to fix?

Replace .filter() followed by [0] or .shift() with .find() to get the first matching element more efficiently.

Non-compliant code example

const item = array.filter(x => isUnicorn(x))[0]; // Noncompliant
const item2 = array.filter(x => isUnicorn(x)).shift(); // Noncompliant

Compliant code example

const item = array.find(x => isUnicorn(x));
const item2 = array.find(x => isUnicorn(x));

Documentation