Skip to content
Advertisement

How can I remove duplicate strings from an array of strings but only if they start with the same 5 characters in JS?

I have a nodelist:

const list = document.querySelectorAll('.list > a')

Every “a” contains a string

In the example the list is like that:

<ul>
<a href="#"><li>Lorem Ipsum dolor</li></a>
<a href="#"><li>Sit Amet Bla bla</li></a>
<a href="#"><li>Sit Ahhh ppppp</li></a>
<a href="#"><li>Loret loops stuff</li></a>
<a href="#"><li>....</li></a>
<a href="#"><li>...</li></a>
<a href="#"><li>.... and so on</li></a>
</ul>

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:

const list = document.querySelectorAll('.list > a');
const set = new Set();

for (const element of list) {
  const prefix = element.innerText.slice(0, 5);
  
  if (set.has(prefix)) {
    element.remove();
  } else {
    set.add(prefix);
  }
}
<ul class="list">
<a href="#"><li>Lorem Ipsum dolor</li></a>
<a href="#"><li>Sit Amet Bla bla</li></a>
<a href="#"><li>Sit Ahhh ppppp</li></a>
<a href="#"><li>Loret loops stuff</li></a>
<a href="#"><li>....</li></a>
<a href="#"><li>...</li></a>
<a href="#"><li>.... and so on</li></a>
</ul>
Advertisement