1

hmm.. I have tried a few things but cant get this to work... I know it should be simpler than I am making it.

I want to create an array without duplicates. Can you help me?

useEffect(() => {
    allBands.forEach(band => {
        if(!availableGenres.includes(band.bandGenre)){
            setAvailableGenres(genres => [...genres, band.bandGenre])  
        }
    })
}, [allBands])
Nick McLean
  • 601
  • 1
  • 9
  • 23
  • Can you provide `allBands`, `genres`, and `availableGenres` please? We don't know what structures you're working with. – Jack Bashford May 06 '20 at 00:16
  • The answer below works -- But I am curious if you had another idea. allBands is an array of objects that each have a bandGenre. I was using the forEach() method to extract the genre from each object in the allBands array. -- availableGenres and setAvailableGenres are part of the useState in react where I was storing the extracted genres. 'genres' is the updator for the state. Thanks for your response! – Nick McLean May 06 '20 at 00:32

2 Answers2

0

I might recommend using the built-in Set object to track unique genres. Once your Set has all the genres, you can use the spread operator (...) to convert it back into an array and set the available genres.

useEffect(() => {
  const genres = new Set();
  allBands.forEach(band => {
    genres.add(band.bandGenre);
  })
  setAvailableGenres([...genres]);
}, [allBands])
Nick
  • 16,066
  • 3
  • 16
  • 32
  • Wow! I have never heard of this one. It works! -- I am reading about it now - I see that it automatically checks to make sure each value is unique? Are there any downsides to using new Set() ? Thanks so much for showing me this. – Nick McLean May 06 '20 at 00:28
  • One downside is that `Set`s are unordered. – Jack Bashford May 06 '20 at 00:33
0

If I am not misunderstanding your data structure, you might try this.

useEffect(() => {
  setAvailableGenres(genres => [
    ...genres, 
    ...allBands.map(band => band.bandGenre).filter(bandGenre => !genres.includes(bandGenre))
])}, [allBands])
Arnas
  • 635
  • 8
  • 18