eslint-plugin-no-array-reduce
ESLint rule to disallow Array.reduce()
method.
Method reduce()
in most cases can be written as map()
, filter()
or one of the for()
loops which benefits in code readability and makes it easier to maintain for future developers.
Subjectively there are still cases where you might want to use reduce()
with eslint-disable
.
There are many debates, discussions and other resources related to it:
Install
npm install --save-dev eslint-plugin-no-array-reduce
Then extend eslint config:
{
"extends": [
"plugin:no-array-reduce/recommended"
]
}
Fail
const products = [
{ name: 'milk', type: 'dairy' },
{ name: 'cheese', type: 'dairy' },
{ name: 'beef', type: 'meat' },
{ name: 'chicken', type: 'meat' },
];
const productsWithPrices = products.reduce((acc, product) => acc.concat({ ...product, price: 2.7 }), []);
const dairies = products.reduce((acc, product) => (product.type === 'dairy' ? acc.concat(product) : acc), []);
const productsByType = products.reduce(
(acc, product) => ({
...acc,
[product.type]: [...(acc[product.type] || []), product],
}),
[],
);
Pass
const productsWithPrices = products.map((product) => ({ ...product, price: 2.7 }));
const dairies = products.filter((product) => product.type === 'dairy');
const productsByType = products.groupBy((product) => product.type);
CodeSandbox
Contributing
All contributions are welcome!