sort-array-includes
💼 This rule is enabled in the following configs: recommended-alphabetical
, recommended-line-length
, recommended-natural
.
🔧 This rule is automatically fixable by the --fix
CLI option.
📖 Rule Details
Enforce sorted array values if the includes
method is immediately called after the array is created.
This rule aims to promote code readability and maintainability by enforcing a consistent ordering of values in arrays.
💡 Examples
js
// ❌ Incorrect
if ([
'maintainer',
'admin',
'developer',
'owner',
'observer'
].includes(user.role)) {
return response.json({ allowed: true })
}
// ✅ Correct
if ([
'admin',
'developer',
'maintainer',
'observer'
'owner',
].includes(user.role)) {
return response.json({ allowed: true })
}
js
// ❌ Incorrect
if ([
'maintainer',
'admin',
'developer',
'owner',
'observer'
].includes(user.role)) {
return response.json({ allowed: true })
}
// ✅ Correct
if ([
'maintainer',
'developer',
'observer'
'admin',
'owner',
].includes(user.role)) {
return response.json({ allowed: true })
}
🔧 Options
This rule accepts an options object with the following properties:
ts
interface Options {
type?: 'alphabetical' | 'natural' | 'line-length'
order?: 'asc' | 'desc'
'ignore-case'?: boolean
'spread-last'?: boolean
}
type
(default: 'alphabetical'
)
alphabetical
- sort alphabetically.natural
- sort in natural order.line-length
- sort by code line length.
order
(default: 'asc'
)
asc
- enforce properties to be in ascending order.desc
- enforce properties to be in descending order.
ignore-case
(default: false
)
Only affects alphabetical and natural sorting. When true
the rule ignores the case-sensitivity of the order.
spread-last
(default: false
)
When true
enforce spread elements in array to be last.
⚙️ Usage
json
// .eslintrc
{
"plugins": ["perfectionist"],
"rules": {
"perfectionist/sort-array-includes": [
"error",
{
"type": "natural",
"order": "asc",
"spread-last": true
}
]
}
}
js
// eslint.config.js
import perfectionist from 'eslint-plugin-perfectionist'
export default [
{
plugins: {
perfectionist,
},
rules: {
'perfectionist/sort-array-includes': [
'error',
{
type: 'natural',
order: 'asc',
spread-last: true,
},
],
},
},
]
🚀 Version
This rule was introduced in v0.5.0.