Cover image for Javascript Pocket Notes

Javascript Pocket Notes

vinicius77 profile image Vinicius Cerqueira Bonifácio ・2 min read

Hi, Devs.

I hope my post finds you all well and health. 🙏

I have been working in some side-projects using the MERN stack plus GraphQL and often my mind forgets the most basic stuff so I decided to write it down somewhere so I have some reference when I have those blackout moments.

In short, my application has books, authors and users collections stored on MongoDB, my backend fetches data from there using GraphQL queries and mutations and finally React renders the data fetched from there in its appropriated components.

I find myself where I wanted to render all books genres (without the duplicated ones) as buttons and filter the books listening those buttons events.

Simple task indeed but I always overthink stuff because actually there are reasons for it when you are developing middle/large applications.

In the end, the solution took me one line of code. 🤦 Of course when implementing it in my React component I will code a little bit more but still.

Let's pretend that I have already fetched the data from MongoDB and it looks like this:

let books = [{
  title: "Eloquent Javascript",
  author: "Marijin Haverbeke",
  genres: ["programming", "web"]
  title: "Python For Data Analysis",
  author: "Wes McKinney",
  genres: ["coding", "finances" , "programming"]

So, in order to give the "label" for the button, I should first have all genres and eliminate somehow the repeated entries:

/** It joins all genres first and after that splits the entries so we have only one array as a result of the map*/ 
let allGenres = books.map(book => book.genres).join(",").split(",")

/** It converts an array of duplicates to a Set. 

Remember that creating a new Set will implicitly remove all the duplicated elements.

And the spread operator converts the set back to an array. */
let noRepeatedGenres = [...new Set(allGenres)]

Cool, right?
But once we understood the concepts why not go for a "Hot Shot"?
There'll go!

/** Superb*/
let allGenres = [...new Set(books.map(book => book.genres).join(",").split(","))]

Having the array properly filtered allows me to finally implement it on my React component.👨‍💻 🙌

I know this post won't change your life at all but as I said before, it can be useful as a future reference if you are struggle with this kind of tasks which at least, in my case, I don't do that often.

Thanks for reading! 🎉

PS:(If you want me to publish more posts like this please let me know in the comments below.)


Editor guide