unicorn/prefer-group-by
eslint-plugin-unicorn
Safe autofix
eslint.config.js
import unicorn from "eslint-plugin-unicorn";
export default [
{
plugins: { unicorn },
rules: {
"unicorn/prefer-group-by": "error",
},
},
];Prefer Object.groupBy() or Map.groupBy() over manual grouping.
const grouped = items.reduce((groups, item) => {
groups[item.type] ??= [];
groups[item.type].push(item);
return groups;
}, {});const grouped = items.reduce((groups, item) => {
if (groups.has(item.category)) {
groups.get(item.category).push(item);
} else {
groups.set(item.category, [item]);
}
return groups;
}, new Map());const groups = {};
for (const item of items) {
groups[item.type] ??= [];
groups[item.type].push(item);
}const grouped = Object.groupBy(items, item => item.type);const grouped = Map.groupBy(items, item => item.category);const groups = Object.groupBy(items, item => item.type);Examples from the ESLint documentation.
unicorn/prefer-group-by
eslint-plugin-unicorn
import unicorn from "eslint-plugin-unicorn";
export default [
{
plugins: { unicorn },
rules: {
"unicorn/prefer-group-by": "error",
},
},
];Oxlint does not have this rule.
Biome does not have this rule.
Prefer .getOrInsertComputed() when the default value has side effects.
Prefer moving code shared by all branches of an if statement out of the branches.
Prefer else if over adjacent if statements with related conditions.
Prefer .getHTML() and .setHTML() over .innerHTML.
Prefer .includes() over repeated equality comparisons.