Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to count values without the duplicate in react

Language used : js with react

I need to count how much "theme" I have but not if he’s already count/exist

data example :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   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 

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading