unicorn/prefer-array-find Perf
What it does
Encourages using Array.prototype.find and Array.prototype.findLast instead of taking the first or last matching element from filter(...).
Why is this bad?
Using filter(...)[0] or array destructuring to get the first match is less efficient and more verbose than using find(...). find and findLast short-circuit when a match is found, whereas filter evaluates the entire array.
Examples
Examples of incorrect code for this rule:
js
const match = users.filter((u) => u.id === id)[0];
const match = users.filter(fn).shift();
const [match] = users.filter(fn);
const match = users.filter(fn).at(-1);
const match = users.filter(fn).pop();Examples of correct code for this rule:
js
const match = users.find((u) => u.id === id);
const match = users.find(fn);
const match = users.findLast(fn);How to use
To enable this rule using the config file or in the CLI, you can use:
json
{
"rules": {
"unicorn/prefer-array-find": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
rules: {
"unicorn/prefer-array-find": "error",
},
});bash
oxlint --deny unicorn/prefer-array-findVersion
This rule was added in v0.16.12.
