Skip to content

Prefer .some(…) over .filter(…).length check and .{find,findLast,findIndex,findLastIndex}(…)

💼 This rule is enabled in the ✅ recommended config.

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

Prefer using Array#some over:

We only check .filter().length > 0 and .filter().length !== 0. These two non-zero length check styles are allowed in unicorn/explicit-length-check rule. It is recommended to use them together.

This rule is fixable for .filter(…).length checks and .{findIndex,findLastIndex}(…).

This rule provides a suggestion for .{find,findLast}(…).

Fail

js
const hasUnicorn = array.filter(element => isUnicorn(element)).length > 0;
js
const hasUnicorn = array.filter(element => isUnicorn(element)).length !== 0;
js
const hasUnicorn = array.filter(element => isUnicorn(element)).length >= 1;
js
if (array.find(element => isUnicorn(element))) {
	// …
}
js
const foo = array.find(element => isUnicorn(element)) ? bar : baz;
js
const hasUnicorn = array.find(element => isUnicorn(element)) !== undefined;
js
const hasUnicorn = array.find(element => isUnicorn(element)) != null;
js
if (array.find(element => isUnicorn(element))) {
	// …
}
js
const foo = array.findLast(element => isUnicorn(element)) ? bar : baz;
js
const hasUnicorn = array.findLast(element => isUnicorn(element)) !== undefined;
js
const hasUnicorn = array.findLast(element => isUnicorn(element)) != null;
js
const hasUnicorn = array.findIndex(element => isUnicorn(element)) !== -1;
js
const hasUnicorn = array.findLastIndex(element => isUnicorn(element)) !== -1;
vue
<template>
	<div v-if="array.find(element => isUnicorn(element))">Vue</div>
</template>
vue
<template>
	<div v-if="array.findLast(element => isUnicorn(element))">Vue</div>
</template>
vue
<template>
	<div v-if="array.filter(element => isUnicorn(element)).length > 0">Vue</div>
</template>

Pass

js
const hasUnicorn = array.some(element => isUnicorn(element));
js
if (array.some(element => isUnicorn(element))) {
	// …
}
js
const foo = array.find(element => isUnicorn(element)) || bar;
js
const foo = array.findLast(element => isUnicorn(element)) || bar;
vue
<template>
	<div v-if="array.some(element => isUnicorn(element))">Vue</div>
</template>

Released under the Apache License 2.0.