Ways to avoid storing repeating paragraphs in JavaScript Array?

Can someone help me with my code? I am struggling to prevent duplicate data from being saved into an array. When I click on any two paragraph elements, the text inside them gets added to an array named `test`. However, I want to avoid saving the same text if I click on a paragraph twice. How can I achieve this and prevent duplicate entries in the array?

var test = [];

[...document.querySelectorAll(".container")].forEach(div => div.addEventListener("click", function(e) {
  if (e.target.tagName === "P") {
    test.push(e.target.textContent);
  }
  console.log(test);
}));
<div class="container">
  <p>
    <b>Group:N</b>Code:1234<br/>
    <b> Session Type:CS<br/>
    <b> Location:Main Hall<br/>
    <b>Time:14:00<br/>
    <b>Day:Tuesday<br/>
    <b>Duration:1hour<br/>
  </p>
</div>
<div class="container">
  <p>
    <b>Group:M</b>Code:98743<br/>
    <b> Session Type:NP<br/>
    <b> Location:Main Hall2<br/>
    <b>Time:11:00<br/>
    <b>Day:Monday<br/>
    <b>Duration:1hour<br/>
  </p>
</div>

Answer №1

To ensure that the array does not already contain the item, you can utilize the Array.prototype.includes method. If the item is not present in the array, then use the push method to add it.

var test = [];
[...document.querySelectorAll(".container")].forEach(div => div.addEventListener("click", function(e) {
  if (e.target.tagName === "P") {
    var text = e.target.textContent;
    if (!test.includes(text)) // Prevents duplicate elements from being added.
      test.push(text);
  }
  console.log(test);
}));
<div class="container">
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <p>Paragraph 3</p>
</div>

Answer №2

By simply clicking on a paragraph, you can add the attribute data-checked. If you click on it again, you can check if e.target.dataset.checked is true and avoid adding it.

var test = [];

[...document.querySelectorAll(".container")].forEach(div => div.addEventListener("click", function(e) {
  if (e.target.tagName === "P" && !e.targed.dataset.checked) {

    test.push(e.target.textContent);
    e.target.dataset.checked = true;
  }
  console.log(test); 
}));
<div class="container">
  <p>
    <b>Group:N</b>Code:1234<br/>
    <b> Session Type:CS<br/>
    <b> Location:Main Hall<br/>
    <b>Time:14:00<br/>
    <b>Day:Tuesday<br/>
    <b>Duration:1hour<br/>
  </p>
</div>
<div class="container">
  <p>
    <b>Group:M</b>Code:98743<br/>
    <b> Session Type:NP<br/>
    <b> Location:Main Hall2<br/>
    <b>Time:11:00<br/>
    <b>Day:Monday<br/>
    <b>Duration:1hour<br/>
  </p>
</div>

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

Automatically populating state and city fields with zip code information

Starting out in the world of web development, I encountered a challenge with a registration form I'm constructing for our company. For guidance, I referred to this resource: http://css-tricks.com/using-ziptastic/. This project marks my initial interac ...

Ensuring the child div's height does not overflow beyond the parent div

When dealing with a parent div and a child div, both having different heights, how can I specifically retrieve the height of the portion of the child div that is within the boundaries of the parent div? Using document.getElementById("id").style.height prov ...

Transfer the chosen language from the uib-dropdown language selector to the $scope variable

Here is a HTML template that allows the user to select a language: <div class="btn-group" uib-dropdown> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" uib-dropdown-toggle> ...

What is the best way to obtain a date in the format of yyyy_mm_dd from a datepicker tool?

I am working with 2 datepickers that have similar structures, but different names. The first one has the id "fecha_1_1" and the second one has the id "fecha_1_2". <div class="col-sm-3"> <p>Desde</p> <div class="f ...

React and Lottie Animation seamlessly synchronized with scrolling movements

I utilized Bodymovin to create various animations and I am hoping to trigger the animation when the scroll reaches that specific point. I have been attempting to find a solution, but unfortunately, I have not been successful. Currently, I am using Gatsby ...

Choose particular content enclosed by two strings (across multiple lines)

Looking to use regex to extract specific text between two strings. For example: foo I have four toys bar //single line foo //multiline I have four toys bar foo I have three pets bar foo I have three pets bar How can I extract the text between & ...

Develop an enhancement for the Date object in Angular 2 using Typescript

Using the built-in Date type, I can easily call date.getDate(), date.getMonth()...etc. However, I am looking for a way to create a custom function like date.myCustomFunctionToGetMonthInString(date) that would return the month in a string format such as &a ...

Instructions on how to implement a readmore button for texts that exceed a specific character length

I am attempting to display a "Read more" button if the length of a comment exceeds 80 characters. This is how I am checking it: <tr repeat.for="m of comments"> <td if.bind="showLess">${m.comment.length < 80 ? m.comment : ...

Revise the text while keeping the column content unchanged

Is it possible to change the text in a column without affecting the image using Jquery? Can this be achieved solely with Jquery without any modifications to the HTML code? Check out the demo $(".jsNoWrap").text("Change text"); <script src="https://a ...

Guide on securely presenting an HTTP-only cookie as a bearer token, without the use of Angular.JS

Can a JWT be securely stored as an HTTP-only cookie and also used as a bearer token without relying on Angular.JS? I believe this could be achievable, as Angular.JS offers similar features (although I'm not sure if they use an HTTP-only cookie to sto ...

What methods can I use to evaluate the efficiency of my website?

Is there a way to assess and improve website performance in terms of load time, render time, and overall efficiency? I've heard of YSLOW for firebug, but am curious if there are any other tools or websites available for this purpose. ...

What is the best way to interact with all the rendered DOM elements in React that were created using the map method

return <div> <div >{'Audios'}</div> {urls.map(url => <div > <audio controls src={url} ref={(element) => this.audioRefs.push(element)} /> </div>)} </div>; I a ...

Restrict the height of posts created in the summernote editor

My goal is to create a structured page application using summernote. When using summernote, a div with contenteditable=true is appended to the body to allow users to add content. However, I want to set a fixed height for this div so that users can only ent ...

Leveraging the power of the Twitter API to integrate real-time tweets into custom code

Looking for an API that can transform a tweet from Twitter into a string format suitable for integration into a program or website. Any recommendations? ...

Maintain the chosen month in every dropdown toggle div in angular 4

While displaying data using toggle options, I am facing an issue where if I click on a different month, all other greyed out headers are displaying the previously selected values. I am trying to figure out a way to keep the value under Selected month as i ...

Utilize Optional Chaining for verifying null or undefined values

I have utilized the following code: data?.response[0]?.Transaction[0]?.UID; In this scenario, the Transaction key is not present, resulting in the error message: ERROR TypeError: Cannot read properties of undefined (reading '0') Instead of chec ...

Firefox and IE are unable to make changes to cssRules

To update existing global CSS rules, I access the document.styleSheets property to locate the rule and make modifications. The selector can be modified by accessing the selectorText property. Sample CSS code: <style type="text/css"> .class { ...

The form validation in Bootstrap 5 seems to be having some trouble triggering

Here is the form setup for allowing users to change their account password: <div class="signup-form-small"> <form method="post" name="frmPassword" id="frmPasswo ...

Only execute the NPM script if there is a staged JavaScript file

How can I ensure that an NPM script runs only when a JS file is staged, specifically after a pre-commit git hook (using Husky)? The scripts in my package.json are as follows: "scripts": { ... "test": "jest", "precommit": "npm test", ... }, ...

Firebase: Saving data to a nonexistent object

I am currently facing a challenge in saving the result of a serviceId to a services object within a parent entity named provider1, especially since the services object has not been initialized yet. The structure of my Firebase data is as follows: "provid ...