I was able to pass writing these lines of codes, but I need some explanation

Tell us what’s happening:
Describe your issue in detail here.
I can’t really explain what’s happening in this part
let filterList = newStr.filter((item,i,newStr) => {
if(item != ‘’){
return newStr
}
});

Your code so far


// Only change code below this line
function urlSlug(title) {
let newStr = title.split(' ');
 let filterList = newStr.filter((item,i,newStr) => {
       if(item != ''){
           return newStr 
       }
 });

return filterList.join('-').toLowerCase();        

}
// Only change code above this line

let result = urlSlug(" Winter Is  Coming");
console.log(result);

Your browser information:

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

Challenge: Apply Functional Programming to Convert Strings to URL Slugs

Link to the challenge:

First, I don’t think newStr is a good name for this variable. The split() method does not return a string, it returns an array. So perhaps something like splitArr instead?

The filter() method tests each element in the array against the function you pass into it and creates a new array out of only those elements that pass test. For your test, if the element is not an empty string then it returns the element, which is coerced into a Boolean value, and since any non-empty string is considered Truthy, it will pass the test and be added to the new array created by filter().

Since you are initially splitting the title by a single space character then your filter is basically not filtering out anything since most of the time words in a string are only separated by one space. But the tests are passing in a title with two spaces between words (in order to trick you) and in this one particular instance your filter actually does something useful because there is an empty string in the array produce by split().

If you add console.logs for the title and then for the array produced by the split() you can see what I am talking about.

Personally, while filter() is doing the job here, it wouldn’t be my first choice. I think there is an easier and more concise way to solve the problem of splitting a string that might have multiple spaces between words. The split() method doesn’t just take strings as arguments, it also takes regular expressions.

1 Like

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