How do you use an arrow function with comparison operator for reduce method?

15.9k Views Asked by At

Using ESLint with Airbnb rules, I can't get a reduce method with comparison operator to work.

In the code below, the array named data holds objects, each with a property named id. The error messages ESLint throws are:

const maxId = data.reduce((prev, current) => {
  return prev.id > current.id ? prev.id : current.id;
});

ESLint Error: arrow-body-style / Unexpected block statement surrounding arrow body.

 const maxId = data.reduce((prev, current) => 
   prev.id > current.id ? prev.id : current.id);

ESLint Error: no-confusing-arrow / Arrow function used ambiguously with a conditional expression.

const maxId = data.reduce(function (prev, current) {
  return prev.id > current.id ? prev.id : current.id;
});

ESLint Error: prefer-arrow-callback / Unexpected function expression.

So how can I get this to work?

2

There are 2 best solutions below

1
On

Wrap the body in parenthesis to make it not "confusing":

(prev, current) => (prev.id > current.id ? prev.id : current.id)
2
On

@Felix has the solution to fix the linter problems, but to make your script work functionally you should use

const maxId = data.reduce((prev, current) => Math.max(prev, current.id), -Infinity);
//                                                    ^^^^             ^^^^^^^^^^^

that will work on data arrays of sizes other than 1 and 2.