arrayFinds
Reports using
.filter()[0]instead of.find()when looking for a single element.
✅ This rule is included in the ts stylistic preset.
When searching for the first item in an array matching a condition, using .filter(...)[0] is less efficient than using .find(...).
The .find() method stops searching after finding the first match, whereas .filter() iterates through the entire array.
Examples
Section titled “Examples”const values = [1, 2, 3, 4, 5];const first = values.filter((value) => value > 3)[0];const users = [{ name: "Alice" }, { name: "Bob" }];const user = users.filter((user) => user.name === "Alice")[0];const values = [1, 2, 3, 4, 5];const first = values.find((value) => value > 3);const users = [{ name: "Alice" }, { name: "Bob" }];const user = users.find((user) => user.name === "Alice");const values = [1, 2, 3, 4, 5];const allPositive = values.filter((value) => value > 0);Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If you intentionally use .filter(...)[0] to execute side effects in the callback on all array elements before returning the first match, you may want to disable this rule.
However, this pattern is unusual and may indicate a need for code refactoring.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”- ESLint:
@typescript-eslint/prefer-find
Made with ❤️🔥 in Boston by
Josh Goldberg and contributors.