What is the best way to remove a specific element from an array?

Imagine you have an array with 5 items, each containing objects. To visually represent this, elements must be created in the document according to the length of the array. Here's how:

let array = [
  {
    "value": "Hello"
  },
  {
    "value": "World"
  },
  {
    "value": "You Can"
  },
  {
    "value": " NOT"
  },
  {
    "value": "<h1>Remove ME!</h1>"
  }
]

// Creating visual elements based on the array.
for(let i = 0; i < array.length; i++) {
  const div = document.createElement("div");
  div.classList.add("DIV");
  div.innerHTML = `
    <span class="Text">${array[i].value}</span>
    <span class="Remove">( Remove )</span>
  `
  document.body.appendChild(div);
}

document.querySelectorAll(".Remove").forEach(elem => {
  elem.addEventListener("click", () => {
    remove();
  }) 
})

function remove() {
  // How do we remove a specific item from the array?
  
}

// I hope this explanation is clear.
/* CSS IS OPTIONAL */

.DIV {
  padding: 10px;
  margin: 10px;
  background: purple;
  color: #fff;
  border-radius: 10px;
  display: flex;
  justify-content: space-between;
}
.Remove {
  cursor: pointer;
  height: fit-content;
}

If you wish to remove the 4th element (with the value "NOT") by clicking its corresponding remove button, how can you achieve that task in all elements?
(Ensure your code works for all elements.) Any assistance will be greatly appreciated. Thank you.

Answer №1

Simplify things by adding an ID or some form of identification and utilizing it in that manner.

let array = [
  {
    "value": "Hello"
  },
  {
    "value": "World"
  },
  {
    "value": "You Can"
  },
  {
    "value": " NOT"
  },
  {
    "value": "<h1>Remove ME!</h1>"
  }
]

// visually creating elements.
for (let i = 0; i < array.length; i++) {
  const div = document.createElement("div");
  div.classList.add("DIV");
  div.innerHTML = `
    <span class="Text">${array[i].value}</span>
    <span class="Remove" data-id="${"elem-" + i}">( Remove )</span>
  `;
  document.body.appendChild(div);
}

document.querySelectorAll(".Remove").forEach(elem => {
  elem.addEventListener("click", () => {
    remove(elem.dataset.id);
  })
})

function remove(id) {
  // Removing a specific item from the array.
  console.log(id);
}

/* CSS IS NOT VERY IMPORTANT */

.DIV {
  padding: 10px;
  margin: 10px;
  background: purple;
  color: #fff;
  border-radius: 10px;
  display: flex;
  justify-content: space-between;
}

.Remove {
  cursor: pointer;
  height: fit-content;
}

The provided code now retrieves the dataset. With this, you can remove the element with that unique ID and update the view accordingly.

let array = [
  {
    "value": "Hello"
  },
  {
    "value": "World"
  },
  {
    "value": "You Can"
  },
  {
    "value": " NOT"
  },
  {
    "value": "<h1>Remove ME!</h1>"
  }
]

function renderElement(array) {
  // visually creating elements.
  for (let i = 0; i < array.length; i++) {
    const div = document.createElement("div");
    div.classList.add("DIV");
    div.innerHTML = `
      <span class="Text">${array[i].value}</span>
      <span class="Remove" data-id="${"elem-" + i}">( Remove )</span>
    `;
    document.body.appendChild(div);
  }
  document.querySelectorAll(".Remove").forEach(elem => {
    elem.addEventListener("click", () => {
      remove(elem.dataset.id);
    })
  });
}

renderElement(array);

function remove(id) {
  // Removing the specific item from the array.
  // Extract the index after removing `elem-` from id.
  array.splice(+id.replace("elem-", ""), 1);
  document.querySelectorAll("body > .DIV").forEach(elem => {
    elem.remove();
  });
  renderElement(array);
}

/* CSS IS NOT VERY IMPORTANT */

.DIV {
  padding: 10px;
  margin: 10px;
  background: purple;
  color: #fff;
  border-radius: 10px;
  display: flex;
  justify-content: space-between;
}

.Remove {
  cursor: pointer;
  height: fit-content;
}

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

Issue with CKEditor 5 in Nuxt 3: "Template or render function for component is not found"

I have successfully installed the required packages: npm i @ckeditor/ckeditor5-build-classic @ckeditor/ckeditor5-vue Next, I integrated it into a component: <template> <div class="w-full h-[400px]"> <CKEditor v-mod ...

Transmitting payment card details to the node

I'm considering utilizing dibs payment dibspayment I came across this Node.js wrapper for the: DIBS API wrapper for Node.js However, using this would involve sending credit card information through a POST request to my node server. My main concern ...

I am struggling to locate the template for my Angular UI modal

I recently developed an app and tried using UI modal, but encountered an issue where the modal function couldn't locate the HTML template. I was able to log messages inside the function but was unable to open a modal view. var app = angular.module(& ...

Incorporating form elements into a Bootstrap pop-over using jQuery AJAX functionality

I am currently working on a webpage that utilizes Bootstrap. My goal is to have users input two pieces of data into a popover similar to a log-in form. The issue arises when I attempt to dynamically create these elements using jQuery. It seems that jQuery ...

`The functionalities of classList.add and classList.remove aren't behaving as anticipated.`

I'm currently working on a list of items (ul, li) that have a class applied to them which adds a left border and bold highlight when clicked. My goal is to reset the style of the previously clicked item back to its original state when a new item is c ...

Display everything when an option is clicked

I have a filter that is working perfectly. When I select a specific category, it filters out only rows with that category. However, I am stuck on how to display all rows again after clicking on the first option. My objective is to show all rows when "Categ ...

Meteor: Incorporating New Fields when Creating an Account

Currently, I am experimenting with the Meteor Roles package found at https://github.com/alanning/meteor-roles in order to add a new field to the user model. The user creation process goes smoothly without any issues, however, the 'roles' field t ...

What happens when a function is called with a local function included in its execution flow?

If I were to execute the code below console.log("Hello World!"); I would expect it to display Hello World!. However, what happens if I include a local function like this? console.log(target, function(err, reply) { console.log("Hello ...

How can you set the Quill text editor to read-only mode in Vue after clicking a button?

I have a quill text editor that I want to customize the default setting to be readonly. When a button is clicked, this setting should toggle between true and false. Here is my component code: <template> <div ref="editor"></div> ...

Conceal and reveal submenu options

I have been exploring a jQuery function that toggles between hiding and showing different divs when a menu item is clicked. However, I am facing an issue where clicking on the same menu item does not close the newly opened div as intended. Additionally, I ...

Creating a virtual whiteboard using a captured screen shot

Can anyone suggest a tool that can enhance my ability to create a feature allowing users to capture screenshots of my website and annotate them with drawings or notes? Are there any existing browser technologies or plugins that offer similar functionality ...

Obtain the last x elements

What is the most efficient way to extract a specific number of elements from the end? <div><span>1</span></div> <div><div>looks like 2</div></div> <div>three!!</div> For instance, how could I re ...

Encountered a 500 status error while trying to send data using Axios in Next.js framework

I'm attempting to create an authentication system using Next.js and TypeScript without utilizing NextAuth. When sending an object with 'username' and 'password' to the register endpoint, I received a 500 status code. Below is the ...

Monitoring changes within a factory

Hey there! I've got this shared_service factory that's being used by my menu and other elements on the page. angular.module('shared_service', []). factory('Shared', function($scope){ var shared_service = { ...

Husky and lint-staged failing to run on Windows due to 'command not found' error

I'm facing issues with getting husky and lint-staged to function properly on my Windows 10 system. Here's how my setup looks like: .huskyrc.json { "hooks": { "pre-commit": "lint-staged" } } .lintstagedrc ( ...

An issue has been identified in the bubble sort algorithm causing certain numerical lists to not be properly sorted when implemented in NodeJS

I am just beginning to learn about algorithms and have started with the bubble sort. I wrote my own implementation and it seems to work well most of the time when sorting a list of numbers from 1 to 100. However, occasionally there is one random number th ...

Tips for verifying login credentials with MongoDB and Express: Leveraging db.collection().findOne() or .find() functions

I am encountering an issue with a POST request involving user credentials being sent from a Login page to the API Server. The code looks like this: loginUser(creds) { //creds is in the form of { username: bob, password: 123 } var request = { ...

What is the most optimal approach to deal with an IndexOutOfBoundsException?

int sum(int[] arr,int size,int suma){ if(size < 0) return suma; return sum(arr,size-1, suma+arr[size]); } Although this code functions properly by halting when the size becomes less than zero, it can lead to a java.lang.IndexOutOfBoundsExcepti ...

How can we ensure that all queries are completed before processing the view in a loop with a MySQL node?

I'm currently facing an issue involving node-mysql and a for loop. My goal is to retrieve an Array or Object of ---------- ---------- URL | COUNT ---------- ---------- from my database, where URLs are pictures intended for use as background i ...

Hmm, seems like there's an issue with the touchable child - it must either be native or forward setNativeProps to

Currently enrolled in a ReactNative course on Coursera, I am facing an error in a 4-year-old course: "Touchable child must either be native or forward setNativeProps to a native component." I am unsure about this error and would greatly appreciate any hel ...