prefer-find
Enforce the use of Array.prototype.find() over Array.prototype.filter() followed by [0] when looking for a single result.
Extending "plugin:@typescript-eslint/stylistic-type-checked"
in an ESLint configuration enables this rule.
Some problems reported by this rule are manually fixable by editor suggestions.
This rule requires type information to run.
When searching for the first item in an array matching a condition, it may be tempting to use code like arr.filter(x => x > 0)[0]
.
However, it is simpler to use Array.prototype.find() instead, arr.find(x => x > 0)
, which also returns the first entry matching a condition.
Because the .find()
only needs to execute the callback until it finds a match, it's also more efficient.
Beware the difference in short-circuiting behavior between the approaches.
.find()
will only execute the callback on array elements until it finds a match, whereas .filter()
executes the callback for all array elements.
Therefore, when fixing errors from this rule, be sure that your .filter()
callbacks do not have side effects.
- ❌ Incorrect
- ✅ Correct
[1, 2, 3].filter(x => x > 1)[0];
[1, 2, 3].filter(x => x > 1).at(0);
Open in Playground[1, 2, 3].find(x => x > 1);
Open in Playgroundmodule.exports = {
"rules": {
"@typescript-eslint/prefer-find": "error"
}
};
Try this rule in the playground ↗
Options
This rule is not configurable.
When Not To Use It
If you intentionally use patterns like .filter(callback)[0]
to execute side effects in callback
on all array elements, you will want to avoid this rule.
Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.
See Troubleshooting > Linting with Type Information > Performance if you experience performance degredations after enabling type checked rules.