Skip to content

Latest commit

 

History

History
74 lines (50 loc) · 1.93 KB

prefer-array-find.md

File metadata and controls

74 lines (50 loc) · 1.93 KB

Prefer .find(…) and .findLast(…) over the first or last element from .filter(…)

💼 This rule is enabled in the ✅ recommended config.

🔧💡 This rule is automatically fixable by the --fix CLI option and manually fixable by editor suggestions.

Array#find() and Array#findLast() breaks the loop as soon as it finds a match and doesn't create a new array.

This rule is fixable unless default values are used in declaration or assignment.

Fail

const item = array.filter(x => isUnicorn(x))[0];
const item = array.filter(x => isUnicorn(x)).shift();
const [item] = array.filter(x => isUnicorn(x));
[item] = array.filter(x => isUnicorn(x));

Pass

const item = array.find(x => isUnicorn(x));
item = array.find(x => isUnicorn(x));
const item = array.findLast(x => isUnicorn(x));

Options

Type: object

checkFromLast

Type: boolean
Default: false

Pass checkFromLast: true to check cases searching from last.

Fail

// eslint unicorn/prefer-array-find: ["error", {"checkFromLast": true}]
const item = array.filter(x => isUnicorn(x)).at(-1);
// eslint unicorn/prefer-array-find: ["error", {"checkFromLast": true}]
const item = array.filter(x => isUnicorn(x)).pop();

Pass

// eslint unicorn/prefer-array-find: ["error", {"checkFromLast": true}]
const item = array.findLast(x => isUnicorn(x));