Explain to me like I'm 5: Why does .fliter in this instance work?

So, I appreciate the help @JeremyLT Gave me in my previous post about this topic here’s the link if you want to see my original problem.

Now here’s my solution:

 Only change code below this line
function urlSlug(title) {


let slu = title
.toLowerCase().split(" ").
filter(str => str !== "")
.join('-');

return slu;

}

// Only change code above this line

It worked after I reshuffled the instances but I’m still a bit confused about the .filter working

If anyone can help clear this up I would greatly appreciate it. Thanks!

Can you explain a little more why you are confused. Do you understand how the filter method works and what it returns?

MDN docs

@bbsmooth
Here’s my interpretation and please correct me if I’m wrong:

let slu = title

.toLowerCase().split(" "). //lowercases each part of string and then splits that string into seperate parts
filter(str => str !== "") //only takes anything that is not a space 
.join('-');// you remove all spaces you replace the spaces with hyphen 

@bbsmooth
I’m thinking the .filter takes all the space out but somehow keeps the separation but when I look at this isn’t filter just taking the string into one big string by removing the spaces? How does .join separate each string to hyphenate it?

Are you sure that’s a space? Looks more like an empty string to me. A space would have a space character in between the double quotes.

Did you look at the docs to see what filter returns? Hint, it isn’t a string :slight_smile:

One thing I would suggest if you have trouble understanding how something works is to separate it out into individual pieces. You don’t always have to be super concise in the beginning. You can always refactor after you get the solution working. So try doing the following:

const slu = title
const afterLowerCase = slu.toLowerCase();
console.log(afterLowerCase);
const afterSplit = afterLowerCase.split(" ");
console.log(afterSplit);
...

Do you see where I’m going here. You can check each intermediate value to see how things work.

Thannks!

Ok I see what your saying. Kinda. So its just taking out empty strings then?

I don’t know what “its” is referring to here. Yes, one of the goals of the function is to replace the space between words with hyphens. So you could say the function is taking out empty strings because it is replacing them with hyphens. But I’m not sure that is what you meant.

Again, redo the code as I suggested, adding a console log after each method and you will see what is happening without having to guess.

Sorry for the miscommunication

By “it” I meant .filter and yes I meant replacing them with hyphens. I will do as you advise LOL :grinning_face_with_smiling_eyes:

Thanks!
Best,
Cy499_Studios

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