Skip to content

arrayFilteredFinds

Reports using .filter() when only the first or last matching element is needed.

✅ This rule is included in the ts logical presets.

Using .filter() to get only the first or last matching element creates an unnecessary intermediate array. The .find() method is more efficient as it stops iteration once a match is found. Similarly, .findLast() is more efficient for finding the last matching element.

This rule reports:

  • .filter()[0] or .filter().shift() or .filter().at(0) → prefer .find()
  • .filter().pop() or .filter().at(-1) → prefer .findLast()
declare const array: number[];
array.filter((value) => value > 0)[0];
declare const array: number[];
array.filter((value) => value > 0).shift();
declare const array: number[];
array.filter((value) => value > 0).at(0);
declare const array: number[];
array.filter((value) => value > 0).pop();
declare const array: number[];
array.filter((value) => value > 0).at(-1);

This rule is not configurable.

If you need the full filtered array for other purposes beyond accessing the first element, you can disable this rule. However, in most cases where only the first match is needed, .find() is the better choice.

Made with ❤️‍🔥 in Boston by Josh Goldberg and contributors.