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();
โšก