Language used : js with react
I need to count how much “theme” I have but not if he’s already count/exist
data example :
movies = [{"id" : 1, "name": "Ps: i love you", "theme": { "id": 1, "name": "love"} }, {"id" : 2, "name": "Holiday", "theme": { "id": 1, "name": "love"} }, {"id" :3, "name": "Scary Movie", "theme": { "id": 2, "name": "horror"} }]
Here, i have two theme : love and horror.
I know how to get the number of theme but i don’t want to count the duplicate, so here i only want to get “2” and no “3” .
what i am actually trying :
const movieTheme= movies.filter((item) => item.theme.name); const movieThemeCount = movieTheme.length; console.log(movieThemeCount ); // of course i'm here getting 3 instead of 2
Advertisement
Answer
There’s a bunch of ways to create a unique list of themes. Use map
and filter
to shape your array however you require it. You should look into the Array.filter method itself, the third parameter self
would have helped you a lot here 🙂
const movies = [ { id: 1, name: 'Ps: i love you', theme: { id: 1, name: 'love' } }, { id: 2, name: 'Holiday', theme: { id: 1, name: 'love' } }, { id: 3, name: 'Scary Movie', theme: { id: 2, name: 'horror' } } ]; const themes = movies .map((movie) => movie.theme) .filter((theme, index, self) => self.findIndex((t) => t.id === theme.id) === index); console.log(themes); // [{"id":1,"name":"love"},{"id":2,"name":"horror"}] console.log(themes.length); // 2