0

I have this array of objects working fine obtained from an API in mounted in Vue.

0:
author: (...)
genre: ("Rock")
poster: (...)
title: (...)
year: (...)

1:
author: (...)
genre: ("Pop")
poster: (...)
title: (...)
year: (...)

2:
author: (...)
genre: ("Jazz")
poster: (...)
title: (...)
year: (...)


3:
author: (...)
genre: ("Rock")
poster: (...)
title: (...)
year: (...)

4:
author: (...)
genre: ("Pop")
poster: (...)
title: (...)
year: (...)

5:
author: (...)
genre: ("Jazz")
poster: (...)
title: (...)
year: (...)


6:
author: (...)
genre: ("Rock")
poster: (...)
title: (...)
year: (...)

7:
author: (...)
genre: ("Pop")
poster: (...)
title: (...)
year: (...)

8:
author: (...)
genre: ("Jazz")
poster: (...)
title: (...)
year: (...)

9:
author: (...)
genre: ("Jazz")
poster: (...)
title: (...)
year: (...)

I have this <select> that I want to fill with the genre seen in the previous array, but without repetitions.

<div class="select-genre">
                <label for="genre">Genre</label>
                <select id="genre" name="genre">
                    <option value="">Seleziona</option>
                    <option v-for="(element, index) in cds" :value="cds.genre">{{ element.genre }}</option>
                </select>
            </div>

The way I did in HTML prints every genre with repetitions, so my idea was to filter the original array to obtain a new one with only the three genres present once. The problem is the original array populates itself after the filter, I've seen its console.log after the filter one, so I did this way to prevent this thing.

if (this.cds.length == 10) {
    const genres = this.cds.filter((element) => {
    return element.genre != element.genre;
}

So it starts to filter only when the original array contains 10 elements. Outside of my if statement I've written:

this.genreArray = [...genres];
console.log('Genere', this.genreArray);

To obtain the genre of the element only when it's different and then I would have saved const genres inside an empty array in data, that is genreArray, to obtain the new array with the genres repeated once. Where have I been wrong?

1
  • 1
    See this previous SO question/answer Commented Apr 28, 2021 at 13:54

1 Answer 1

0

Your filter function is not correct. the element.genre != element.genre condition is always false because it is comparing the same element to itself each time.

you can do something like this:

if (this.cds.length == 10) {
    const genres = {};
    this.cds.forEach((element) => {
       if(!genres[element.genre]) {
          genres[element.genre] = element;
       }
    });
}
this.genreArray = Object.values(genres);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.