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.
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:
.filter() continues processing even after finding matches, while .find() stops immediately upon finding the first matchThe .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.
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.
Replace .filter() followed by [0] or .shift() with .find() to get the first matching element more efficiently.
const item = array.filter(x => isUnicorn(x))[0]; // Noncompliant const item2 = array.filter(x => isUnicorn(x)).shift(); // Noncompliant
const item = array.find(x => isUnicorn(x)); const item2 = array.find(x => isUnicorn(x));