Scenario
I am in the process of creating a basic webpage that will allow me to showcase and filter bookmarks. Each bookmark can be associated with multiple tags, and tags may be duplicated across different bookmarks. The tags for each bookmark are stored in a data attribute within the wrapper element for that bookmark (as shown below). My ultimate objective is to dynamically generate a menu containing all the tags present on the page and toggle their visibility based on user selections. I am keen on keeping this project simple and self-contained, so I prefer solutions using pure JavaScript over external libraries.
Issue
Currently, my main challenge lies in generating a comprehensive array of tags. While I have successfully filtered out undefined elements (when a bookmark has no tags) and removed duplicate tags, I am struggling when it comes to handling bookmarks with multiple tags. Since a data attribute can only be used once per element, all tags for a single bookmark need to be stored as a list within the data attribute.
My goal is to split multiple tags from a singular data attribute entry into separate elements within the array for every bookmark with more than one tag.
For reference, consider the "data-tags"
attribute in the <article>
element:
<article class="note"
data-date="2021-08-04T03:40"
data-tags="Tag-One Tag-Two">
<section class="item">Bookmark Description</section>
<section class="tags">
<a href="#" class="tag">Tag-One</a>
<a href="#" class="tag">Tag-Two</a>
</section>
</article>
The first part of my script is functional:
const notes = document.querySelectorAll('.note');
let tags = [];
// extract tags
notes.forEach(note => tags.push(note.dataset.tags));
//Resulting array format: tags[] = ("Tag-One Tag-Two")
//remove duplicates
tags = tags.filter((value,index,array) => array.indexOf(value) == index);
//remove undefined values
tags = tags.filter(tag => tag !== undefined);
However, the following section poses challenges. Despite attempting various looping techniques, the utilization of splice()
does not yield the expected results - often leading to premature trimming of the array:
for (let index = 0; index < tags.length; index++) {
var value = tags[index];
if (value.indexOf(' ') > 0 ){
var newTags = value.split(' ');
newTags.forEach(newTag => tags.push(newTag));
tags.splice(index,1);
}
}
Any assistance offered would be greatly valued. Feel free to critique the initial code as well!