Skip to content

Latest commit

Β 

History

History
62 lines (40 loc) Β· 1.81 KB

File metadata and controls

62 lines (40 loc) Β· 1.81 KB

prefer-array-find

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

πŸ’Ό This rule is enabled in the following configs: βœ… recommended, β˜‘οΈ unopinionated.

πŸ”§πŸ’‘ 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.

Examples

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

// ❌
const item = array.filter(x => isUnicorn(x)).shift();

// ❌
const [item] = array.filter(x => isUnicorn(x));

// βœ…
const item = array.find(x => isUnicorn(x));
// ❌
const item = array.filter(x => isUnicorn(x)).at(-1);

// ❌
const item = array.filter(x => isUnicorn(x)).pop();

// βœ…
const item = array.findLast(x => isUnicorn(x));

Options

Type: object

checkFromLast

Type: boolean
Default: true

Pass checkFromLast: false to disable check cases searching from last.

/* eslint unicorn/prefer-array-find: ["error", {"checkFromLast": false}] */

// βœ…
const item = array.filter(x => isUnicorn(x)).at(-1);

// βœ…
const item = array.filter(x => isUnicorn(x)).pop();