carneiro_squared
carneiro_squared

Reputation: 23

Having trouble working with filter method in JavaScript

I'm currently taking a JavaScript course and stuck on an exercise where i should create a function that, when applied to an array, returns a new array filtered with only the strings with less than 10 characters.

after some attempts i was certain that this would be the one, but failed.

function validUserNames(array) {
   return array.filter(function(el) { el.length < 10 } );
}  

Anyone can help with it?

Upvotes: 0

Views: 1548

Answers (2)

Paul Rooney
Paul Rooney

Reputation: 21619

This works ok.

function validUserNames(array) {
   return array.filter(function(el) { return el.length < 10 } );
}

console.log(validUserNames(['foo', 'bar', 'baz', 'foobarbazzz']));

Just add a return inside the filter function. Without it returns undefined. filter requires you to provide it with a predicate function, which is a function that returns true or false. When it returns true it is included in the result, when it returns false it is not included. undefined seems to cause it to not be included.

You can use more concise syntax which avoids the need for the return by using an arrow function, without curly braces.

i.e.

return array.filter(el => el.length < 10);

When you add back the curly braces (say your function spans multiple lines) the return statement needs to included.

i.e.

return array.filter(el => { return el.length < 10 });

Upvotes: 1

3limin4t0r
3limin4t0r

Reputation: 21160

The issue is that filter expects a function that returns a truthy or falsy value. You currently don't return anything from the provided function, meaning that the return value is always undefined (falsy). Which will result in an empty array after filtering.

You should add a return statement within the provided function passed to filter:

function validUserNames(array) {
  return array.filter(function(el) { return el.length < 10 } );
}

Or use an arrow function without brackets ({ and }) to implicitly return:

function validUserNames(array) {
  return array.filter(el => el.length < 10);
}

Upvotes: 0

Related Questions