unicorn/no-array-reduce
Disallow reduce() and reduceRight() in favor of a loop
To read a reduce(), you have to follow the accumulator through every return in the callback, and its starting value comes last, after the callback. Written as a for...of loop, the same code names the result first and updates it in plain statements.
A callback that only combines two values with an operator, such as a sum, is allowed by default.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"unicorn/no-array-reduce" = "error" # or "warn"Every option, set to its default:
bunfig.toml
[lint.rules]
"unicorn/no-array-reduce" = ["error", {
allowSimpleOperations = true,
}]Examples#
example.js1 problem
const byId = users.reduceDon't use Array#reduce() and Array#reduceRight(), use for loops instead.((result, user) => {
result[user.id] = user;
return result;
}, {});example.jsNo problems
const byId = {};
for (const user of users) {
byId[user.id] = user;
}example.jsNo problems
const total = prices.reduce((sum, price) => sum + price, 0);Options#
| Option | Default | What it does |
|---|---|---|
allowSimpleOperations | true | Allow a callback that only returns a binary expression, such as a + b or a * b. |
example.jswith
{ "allowSimpleOperations": false }1 problemconst total = prices.reduceDon't use Array#reduce() and Array#reduceRight(), use for loops instead.((sum, price) => sum + price, 0);