Home > Net >  How to count values without the duplicate in react
How to count values without the duplicate in react

Time:11-11

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 

CodePudding user response:

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

CodePudding user response:

I edited your code, try this, it is tested

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 movieTheme = []

movies.forEach((item) => {
   let exists = false
   for (let i = 0; i < movieTheme.length; i  ) {
    if (movieTheme[i] === item.theme.name) {
        exists = true;
    }
}
if (exists) {
    return false
} else {
    movieTheme.push(item.theme.name)
    return item.theme.name;

}
});
const movieThemeCount = movieTheme.length;

console.log(movieTheme); 
console.log(movieThemeCount); 

CodePudding user response:

I writed what you need inside handleCountTheme function. It just use one loop inside to count the number of theme.

 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 handleCountTheme = (movies) => {
    const idList = []
    movies.forEach((item) => { 
        if(idList.includes(item.theme.id)) return;
        idList.push(item.theme.id);
    }) 
    return idList.length;
}

console.log(handleCountTheme(movies))

  • Related