I have a nodelist:
JavaScript
x
2
1
const list = document.querySelectorAll('.list > a')
2
Every “a” contains a string
In the example the list is like that:
JavaScript
1
10
10
1
<ul>
2
<a href="#"><li>Lorem Ipsum dolor</li></a>
3
<a href="#"><li>Sit Amet Bla bla</li></a>
4
<a href="#"><li>Sit Ahhh ppppp</li></a>
5
<a href="#"><li>Loret loops stuff</li></a>
6
<a href="#"><li> .</li></a>
7
<a href="#"><li></li></a>
8
<a href="#"><li> . and so on</li></a>
9
</ul>
10
I need to remove for example the the third element because it starts with the same 5 characters of the second element even though they end differently.
Everytime I encounter a new element I need to check if there’s another element in the same list starting with the same 5 characters and remove it.
Hope it’s clear.
Advertisement
Answer
Just loop over the elements and use a Set
to collect the prefixes:
JavaScript
1
12
12
1
const list = document.querySelectorAll('.list > a');
2
const set = new Set();
3
4
for (const element of list) {
5
const prefix = element.innerText.slice(0, 5);
6
7
if (set.has(prefix)) {
8
element.remove();
9
} else {
10
set.add(prefix);
11
}
12
}
JavaScript
1
9
1
<ul class="list">
2
<a href="#"><li>Lorem Ipsum dolor</li></a>
3
<a href="#"><li>Sit Amet Bla bla</li></a>
4
<a href="#"><li>Sit Ahhh ppppp</li></a>
5
<a href="#"><li>Loret loops stuff</li></a>
6
<a href="#"><li> .</li></a>
7
<a href="#"><li></li></a>
8
<a href="#"><li> . and so on</li></a>
9
</ul>