Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 754
gwvt Avatar asked Dec 27 '16 17:12

gwvt


People also ask

Can I use arrow functions in methods?

Arrow functions cannot be used to write object methods because, as you have found, since arrow functions close over the this of the lexically enclosing context, the this within the arrow is the one that was current where you defined the object.

How do you use this in arrow function?

In short, with arrow functions there are no binding of this . In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever. With arrow functions the this keyword always represents the object that defined the arrow function.

What does () => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

What does => mean in programming?

What It Is. This is an arrow function. Arrow functions are a short syntax, introduced by ECMAscript 6, that can be used similarly to the way you would use function expressions. In other words, you can often use them in place of expressions like function (foo) {...} .


2 Answers

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

(prev, current) => (prev.id > current.id ? prev.id : current.id)
like image 164
Felix Kling Avatar answered Nov 07 '22 04:11

Felix Kling


@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.

like image 43
Bergi Avatar answered Nov 07 '22 03:11

Bergi