How to use ES6 Fat Arrow to .filter() an array of objects

I’m trying to use ES6 arrow function with .filter to return adults (Jack & Jill). It appears I cannot use an if statement.

What do I need to know in order to do this in ES6?

var family = [{"name":"Jack",  "age": 26},
              {"name":"Jill",  "age": 22},
              {"name":"James", "age": 5 },
              {"name":"Jenny", "age": 2 }];

let adults = family.filter(person => if (person.age > 18) person); // throws error

(8:37) SyntaxError: unknown: Unexpected token (8:37)
|let adults = family.filter(person => if (person.age > 18) person);

My working ES5 example:

let adults2 = family.filter(function (per) {
  if (per.age > 18) { return per; }
});

You don’t need if. You can return the condition directly.

1 Like

Filter expect a Boolean, so you can just return person.age > 18

Your issue with that syntax is that it is too complex to use the implicit return statement, so you need to put the body of the function inside curly brackets and explicitly use the return keyword.

Putting aside that filter has to return true or false, if is a statement, not an expression. An expression is something that resolves to value (and any expression can be used in place of a value) - myVariable, 1 + 1, myFunction(a, b). A statement is an instruction to the program to perform some action, it doesn’t resolve to a value at all. if, while, for, do, return, throw, yield and so on are all statements, they just tell the JS interpreter to do something

With that in mind, what you’ve written doesn’t make any sense. It’s like writing return for (var i = 0..... or return return someThing

So

family.filter(person => if (person.age > 18) person);

It’s throwing an error in that function, when it hits the if. So the function is

person => if (person.age > 18) person

Which can be written

function personOver18 (person) {
  return if (person.age > 18) person;
}

You can’t return an if statement, there is nothing to return, it doesn’t make sense.