Filter function explaination

Tell us what’s happening:
So in this challenge:

https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/apply-functional-programming-to-convert-strings-to-url-slugs

I have solved it my way already as I show.

But looking at the suggested solution:

return title.split(/\W/).filter((obj)=>{
    return obj !=='';
  }).join('-').toLowerCase();

I can’t understand what is filter doing here, what does obj !==’’ ask for? I understand it filters null characters, but it is actually trimming, so I can’t get it

anyone care to explain?

Thanks

Your code so far


// the global variable
var globalTitle = " Winter Is   Coming";

// Add your code below this line
function urlSlug(title) {

return title.trim().toLowerCase().split(/\W+/).join("-");

  


}
// Add your code above this line

var winterComing = urlSlug(globalTitle); // Should be "winter-is-coming"

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/apply-functional-programming-to-convert-strings-to-url-slugs

The string can have extra spaces, the filter will remove the empty string elements from the array split gives you.

const textArrayNormalString = 'this is some text'.split(/\W/)
console.log(textArrayNormalString);
["this", "is", "some", "text"]

const textArrayWithSpaces = 'this  is  some  text with extra spaces  '.split(/\W/)
console.log(textArrayWithSpaces);
["this", "", "is", "", "some", "", "text", "with", "extra", "spaces", "", ""]

const textArraySpacesRemoved = textArrayWithSpaces.filter(word => word !== '')
console.log(textArraySpacesRemoved);
["this", "is", "some", "text", "with", "extra", "spaces"]

String.prototype.split() splits a String object into an array of strings, using a specified separator string to determine where to make each split. If separator is a regular expression that contains capturing parentheses (), matched results are included in the array. In other case separator is (/\W/) not (/(\W)/), it means that non-word characters are not included.
With Array.prototype.filter() we return all objects of array that are not empty spaces
Array.prototype.join() returns aray as a string. In other case we pass a join parameter as a hyphen symbol. A new string has hyphens between words.
String.prototype.toLowerCase() makes all characters of our string lower case.

You are using String.prototype.trim() that removes whitespaces from both ends of a string.