Using filter in an array

Hello !
I have written an array.
oldArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

I want to filter the numbers greater than 5.
I proposed a first solution:

let newArray = oldArray.filter(function(x) {
return x > 5;
};

and it worked. it outputs [ 6, 7, 8, 9, 10]
But, since I want to familiarize myself with the arrow functions.
I proposed this as a solution:
let newArray = oldArray.filter(x => ({x > 5}));
but apparently it didn’t work. (syntax error)
I try this also: let newArray = oldArray.filter(x => (x > 5));
It didn’t work too.
Can someone please explain me why?

This won’t work because the ({ tells it that you want to implicit return an object and x > 5 is not valid for the insides of an object literal.

This:

let newArray = oldArray.filter(x => (x > 5));

works for me. I don’t know why it didn’t work for you.

const oldArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let newArray = oldArray.filter(x => (x > 5));

console.log(newArray);
// [6, 7, 8, 9, 10]

The parentheses are redundant, this would work too:

let newArray = oldArray.filter(x => x > 5);
2 Likes

It was my mistake. I work on vscode and I forgot the command + s before outputing my result.
Thank you, it is very helpful.
I really like the last solution :smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.