I successfully retrieved an array of objects from an API in mounted
within Vue. The array consists of various objects with properties such as author, genre, poster, title, and year.
0:
author: (...)
genre: ("Rock")
poster: (...)
title: (...)
year: (...)
1:
author: (...)
genre: ("Pop")
poster: (...)
title: (...)
year: (...)
2:
author: (...)
genre: ("Jazz")
poster: (...)
title: (...)
year: (...)
...
I have a <select>
element that I want to populate with the unique genres present in the array mentioned above. However, I do not want any genre to be repeated.
<div class="select-genre">
<label for="genre">Genre</label>
<select id="genre" name="genre">
<option value="">Select</option>
<option v-for="(element, index) in cds" :value="cds.genre">{{ element.genre }}</option>
</select>
</div>
The current implementation lists every genre multiple times due to repetitions. My approach involves filtering out duplicate genres from the original array to create a new array containing each genre only once. However, the issue arises when the original array refreshes itself post-filtering, making it challenging to generate the desired result.
if (this.cds.length == 10) {
const genres = this.cds.filter((element) => {
return element.genre != element.genre;
}
To address this problem, I set up a conditional statement to trigger the filtering process only when the original array contains exactly 10 elements. Following the filter operation, I assign the filtered genres to a separate variable and log its contents to prevent data manipulation.
this.genreArray = [...genres];
console.log('Genres', this.genreArray);
My intention was to store the unique genres in a dedicated array (genreArray
) after checking for duplicates per element. However, it seems there might be a flaw in my logic. Can you spot where I went wrong?