Skip to content

Latest commit

 

History

History
80 lines (55 loc) · 1.89 KB

no-array-reduce.md

File metadata and controls

80 lines (55 loc) · 1.89 KB

Disallow Array#reduce() and Array#reduceRight()

💼 This rule is enabled in the ✅ recommended config.

Array#reduce() and Array#reduceRight() usually result in hard-to-read and less performant code. In almost every case, it can be replaced by .map, .filter, or a for-of loop.

It's only somewhat useful in the rare case of summing up numbers, which is allowed by default.

Use eslint-disable comment if you really need to use it or disable the rule entirely if you prefer functional programming.

This rule is not fixable.

Fail

array.reduce(reducer, initialValue);
array.reduceRight(reducer, initialValue);
array.reduce(reducer);
[].reduce.call(array, reducer);
[].reduce.apply(array, [reducer, initialValue]);
Array.prototype.reduce.call(array, reducer);

Pass

// eslint-disable-next-line unicorn/no-array-reduce
array.reduce(reducer, initialValue);
array.reduce((total, value) => total + value);
let result = initialValue;

for (const element of array) {
	result += element;
}

Options

allowSimpleOperations

Type: boolean
Default: true

Allow simple operations (like addition, subtraction, etc.) in a reduce call.

Set it to false to disable reduce completely.

// eslint unicorn/no-array-reduce: ["error", {"allowSimpleOperations": true}]
array.reduce((total, item) => total + item) // Passes
// eslint unicorn/no-array-reduce: ["error", {"allowSimpleOperations": false}]
array.reduce((total, item) => total + item) // Fails