useFind
Summary
Section titled “Summary”- Diagnostic Category:
lint/nursery/useFind - This rule doesn’t have a fix.
- The default severity of this rule is information.
- This rule belongs to the following domains:
- Sources:
- Same as
@typescript-eslint/prefer-find
- Same as
How to configure
Section titled “How to configure”{ "linter": { "rules": { "nursery": { "useFind": "error" } } }}Description
Section titled “Description”Enforce the use of Array.prototype.find() over Array.prototype.filter() followed by [0] when looking for a single result.
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.
Examples
Section titled “Examples”Invalid
Section titled “Invalid”[1, 2, 3].filter(x => x > 1)[0];/invalid.ts:1:1 lint/nursery/useFind ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ℹ Prefer using Array#find() over Array#filter[0].
> 1 │ [1, 2, 3].filter(x => x > 1)[0];
│ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2 │
ℹ Use Array#find() instead of Array#filter[0] to improve readability.
[1, 2, 3].filter(x => x > 1).at(0);/invalid2.ts:1:1 lint/nursery/useFind ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ℹ Prefer using Array#find() over Array#filter[0].
> 1 │ [1, 2, 3].filter(x => x > 1).at(0);
│ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2 │
ℹ Use Array#find() instead of Array#filter[0] to improve readability.
[1, 2, 3].find(x => x > 1);Related links
Section titled “Related links”Copyright (c) 2023-present Biome Developers and Contributors.