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:

JavaScript

Every “a” contains a string

In the example the list is like that:

JavaScript

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
JavaScript
Advertisement