What is the best way to eliminate duplicated strings from an array in JavaScript, specifically ones that share the same initial 5 characters?

I am facing a challenge with a nodelist:

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

Each "a" tag contains a string value.

An example of the list structure is as follows:

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

My goal is to remove duplicates based on the first 5 characters of each string. For instance, if two strings start with the same 5 characters, I need to keep only one of them.

Each time I encounter a new element, I must compare it with existing elements in the list and remove any duplicates with the same initial 5 characters.

I hope this explanation clarifies the situation.

Answer №1

To get rid of duplicates, iterate through the elements and utilize a Set to store 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Send information to a Google form using AJAX requests

I have encountered an issue while attempting to send data via AJAX to a Google form. Despite receiving a success message with a statusCode of 0, the data does not show up in the form: var dat={ "entry.529474552" :"data1", "entry.1066559787": "name1"}; pos ...

Unable to showcase angularJS scope elements

I'm currently working on a web application that combines AngularJS and Laravel. The main functionality of the application is to allow users to post notes on a shared board. However, I've encountered an issue where the submitted note gets saved to ...

Rearrange the order of items in the fancybox gallery

Typically, fancybox displays items in the gallery based on the order they are added in the HTML code. Is there a way to customize the order of items when they are opened in the popup, while keeping the original order when displayed on the page? The solut ...

Javascript SVG object reference

I am facing an issue. I created a sketch using another program and saved it as an svg file. Now, I want to display this file on a website. I have created a div with an id and used JavaScript to load the svg file into that div. However, when trying to a ...

Implementing a breadcrumb-style back button using jQuery

The menu is currently displayed on the left side without any issues. My next task involves implementing a back button functionality. When a user clicks from Demo1 to Demo 1.1, additional options like Demo 1.1.1 and Demo 1.1.2 will appear. To facilitate nav ...

Using JavaScript to convert date and time into ISO format

Similar Question: How do I output an ISO-8601 formatted string in Javascript? I've been attempting to change a date and time input into an ISO format but keep encountering the error .toISOString is undefined. It seems like I must be overlooking s ...

Vue.js Pagination Issue - Current Page Number Beyond Maximum Page Limit

I'm currently working on incorporating pagination into a table showcasing data for Magic: The Gathering cards. By default, the table displays only 5 items per page, with options to select pages and set the number of results per page at the bottom of ...

The request does not include the cookies

My ReactJS client sends a cookie using this NodeJS code snippet: res.cookie("token", jwtCreation, { maxAge: 24 * 60 * 60 * 1000, // Milliseconds (24 hours) sameSite: 'None', // Cross-site requests allowed for modern browser ...

Next.js does not support Video.js functionality when using server side rendering

I'm struggling to set up video.js in my next.js project and encountering issues. When the player is loading, it initially appears black and then disappears abruptly. A warning message in the console reads: "video.es.js?31bb:228 VIDEOJS: WARN: T ...

Creating an HTTP interceptor in Backbone: A step-by-step guide

After gaining experience with backbone, I decided to delve into learning angular. The features of angular really caught my interest, especially the HTTP interceptor. I began thinking about how to implement this functionality in backbone to display a spin ...

Error message encountered in Quagga JavaScript barcode scanner: "Uncaught TypeError: Quagga.init is not defined."

I'm currently facing a challenge with implementing barcode scanning functionality into my website using vanilla JavaScript. I've been trying to utilize the Quagga JavaScript library, but I seem to be stuck at the initial step. Here's the cod ...

Performing an Ajax post request to a PHP script in order to retrieve a PHP variable using XMLHttpRequest

I am looking to dynamically update my table using JavaScript every few seconds. Currently, I have set up an AJAX post request to my update.php file and trigger it if it is set. Then, I execute a MySQL query to retrieve the data and store the resultset in ...

What is the best way to hide a form box and button after clicking a button?

I'm creating a simple form in HTML and JavaScript where users can input their name and have it displayed. My goal is to hide the form and button once the user submits. <form> <br/>Please enter your name: <input type="text" id="name ...

Inability to submit page after clicking on lower half of button while eliminating validations

In my current Struts2 application, I am encountering a issue related to validations on textfields. The validations include checks for missing values and incorrect values. Below these fields, there is a button that should submit the form once all validation ...

Enhancing security with Mongoose's bcrypt for asynchronous password setting and saving

I've defined a mongoose schema that includes a method to set a password using bcrypt: UserSchema.methods.setPassword = function (password) { bcrypt.hash(password, saltRounds).then(function (hash) { this.hash = hash; }); }; When creating a us ...

What limitations prevent me from using "await .getAttribute()" in Protractor, despite the fact that it does return a promise?

I have been working on transitioning my Protractor tests from using the selenium control flow to async/await. However, I am facing an issue where it is not allowing me to use await for the .getAttribute() function. Each time I try, I receive the error mess ...

Encountering Angular 8 Issue: "ERROR Error: 'Cannot locate control with name: 'getAccountArr'' when Implementing Form Array"

I am currently working on an Angular 8 project where I need to render a list of inputs prepopulated with JSON data using Reactive Forms. The mapping of the types array and storing it in the group seems to be working fine. However, I suspect there might be ...

Tricks to avoid using useEffect dependency in custom hook

Take a look at this snippet of code I have written: const { getConversionList, conversionList } = useConversion(); useEffect(() => { getConversionList(); }, []); I am using useConversion as a GraphQL resolver hook, however, I am encountering a Linti ...

Adding elements to a global array via a callback function in JavaScript: A step-by-step guide

I am currently working on querying and adding users to a global array from my database. My goal is to store the elements in this global array so that I can access it from any part of my application. app.get("/admin/orders", (req, res) => { Q ...

Sending a POST request to an API with Angular and passing an object as the payload

I'm currently working on adding a feature to my app where I can take the products from an order and send them to the cart, essentially replicating the entire order. While I have successfully retrieved the order, I am facing difficulty in sending it b ...