Home > Enterprise >  Deleting an element from an array in JavaScript
Deleting an element from an array in JavaScript

Time:10-01

I am making a 'to-do' web page and there I am adding all the tasks into an array. Now, to delete an already added task, I have tried to use Splice, Shift and remove but none are deleting the task at the desired index as well as the card from UI. Would be thankful for any help as I am total beginner.

let addbtn=document.getElementById('addbtn')
addbtn.addEventListener('click',addnotes)
var nodeadd=[];

var arr;
var result;
var unique;
function addnotes(){
    console.log("I am adding");
    let addtxt=document.getElementById('addTxt');
    nodeadd.push(addtxt.value);
  unique=[...new Set(nodeadd)];
   //arr=unique.join("").trim().split(' ');
  // result=unique.filter((item)=>item!=' ');
   console.log("I am texting",unique);
   addtxt.value="";
 showNotes();
}

function showNotes(){
    let html="";
    console.log("I am getting",unique);
   //result=unique.join("").trim().split(' ');
    //const result=unique.filter((item)=>item!=' ');
    result = unique.filter(unique => unique.trim().length > 0);
    console.log("I am result",result);
     
    result.forEach((element,index) => {
        console.log("I am calling")
        console.log(element,index);
        html =`<div class="nodeCard my-2 mx-2 card" style="width: 18rem;">
        <div class="card-body">
          <h5 class="card-title">${index}</h5>
          <p class="card-text">${element}</p>
          <button  id="${index}" onclick="deleteNote(this.id)" class="btn btn-primary">Delete note</a>
        </div>
      </div>`
    });
   let ele=document.getElementById('notes');
   if(result.length!=0){
       ele.innerHTML=html;
   }
  }
  function deleteNote(index){
   for(let i=0;i<result.length;i  ){
     //console.log("I am  logging");
     //console.log("index",i);
     //console.log("indexing",index);
     console.log(index);
     if(i==index){
       //console.log("I am getting index",i,index);
       result.splice(i,1);
     // result.shift();
     }
   }

  }
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
</head>
<body>
  <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container-fluid">
      <a class="navbar-brand" href="#">Navbar</a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="#">Home</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Link</a>
          </li>
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
              Dropdown
            </a>
            <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
              <li><a class="dropdown-item" href="#">Action</a></li>
              <li><a class="dropdown-item" href="#">Another action</a></li>
              <li><hr class="dropdown-divider"></li>
              <li><a class="dropdown-item" href="#">Something else here</a></li>
            </ul>
          </li>
          <li class="nav-item">
            <a class="nav-link disabled">Disabled</a>
          </li>
        </ul>
        <form class="d-flex">
          <input class="form-control me-2" id="search" type="search" placeholder="Search" aria-label="Search">
          <button class="btn btn-outline-success" type="submit">Search</button>
        </form>
      </div>
    </div>
  </nav>
  <div class="container my-3">
    <h1>Welcome to magic notes</h1>
    <div class="card" style="width: 18rem;">
      <div class="card-body">
        <h5 class="card-title">Add a note</h5>
        <div class="mb-3">
          <label for="exampleFormControlTextarea1" class="form-label">Example textarea</label>
          <textarea class="form-control" id="addTxt" rows="3"></textarea>
        </div>
        <button  class="btn btn-primary" id="addbtn">Add note</a>
      </div>
    </div>
    <h2>Notes</h2>
    <hr/>
    <div id="notes" class="row container-fluid">
    </div>
    <script src="app.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-W8fXfP3gkOKtndU4JGtKDvXbO53Wy8SZCQHczT5FMiiqmQfUpWbYdTil/SxwZgAN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-skAcpIdS7UcVUC05LJ9Dxay8AXcDYfBJqt1CJ85S/CFujBsIzCIv l9liuYLaMQ/" crossorigin="anonymous"></script>
</body>
</html>

CodePudding user response:

Use arr.filter instead of splice. you can also read docs on arr.filter from MDN it will be helpful to you.

For example

const updatedarr = oldarr.filter((item) => item.id ===id )
// filter returns a new array containing the elements that meet the condition in the function passed to it

CodePudding user response:

You need to add ID to new element and then remove it by this ID from DOM. Check triple-line // comments inline.

As for array, basically splice is right, but you need to handle last array element and not forget about nodeadd array

BUT - keep in mind, that you removing notes by their ID, so if you first remove id 0, then after splice your prev id 1 will become id 0, but your button will reference to id 1 - this will prevent elements from removing. Try to update this code, so element id's will be refreshed each time you remove note.

let addbtn=document.getElementById('addbtn')
addbtn.addEventListener('click',addnotes)
var nodeadd=[];

var arr;
var result;
var unique;
function addnotes(){
    console.log("I am adding");
    let addtxt=document.getElementById('addTxt');
    nodeadd.push(addtxt.value);
  unique=[...new Set(nodeadd)];
   //arr=unique.join("").trim().split(' ');
  // result=unique.filter((item)=>item!=' ');
   console.log("I am texting",unique);
   addtxt.value="";
 showNotes();
}

function showNotes(){
    let html="";
    console.log("I am getting",unique);
   //result=unique.join("").trim().split(' ');
    //const result=unique.filter((item)=>item!=' ');
    result = unique.filter(unique => unique.trim().length > 0);
    console.log("I am result",result);
     
    result.forEach((element,index) => {
        console.log("I am calling")
        console.log(element,index);
        //
        // Add ID to html element
        //
        html =`<div id="noteId-${index}" class="nodeCard my-2 mx-2 card" style="width: 18rem;">
        <div class="card-body">
          <h5 class="card-title">${index}</h5>
          <p class="card-text">${element}</p>
          <button  id="${index}" onclick="deleteNote(this.id)" class="btn btn-primary">Delete note</a>
        </div>
      </div>`
    });
   let ele=document.getElementById('notes');
   if(result.length!=0){
       ele.innerHTML=html;
   }
   //
   // Log results
   //
   console.log(result);
  }
  function deleteNote(index){
   for(let i=0;i<result.length;i  ){
     //console.log("I am  logging");
     //console.log("index",i);
     //console.log("indexing",index);
     console.log(index);
     if(i==index){
       //console.log("I am getting index",i,index);
       //
       // Check if last result
       //
       if(result.length === 1) {
         result.splice(-1);
         // also splice nodeadd array
         nodeadd.splice(-1);
       } else {
         result.splice(i,1);
         // also splice nodeadd array
         nodeadd.splice(i,1);
       }
       break;
     // result.shift();
     }
   }
   //
   // Log results
   //
   console.log(result);
   //
   // Remove element from DOM by ID
   //
   document.getElementById(`noteId-${index}`).remove();
   //
   //
   //
  }
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
</head>
<body>
  <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container-fluid">
      <a class="navbar-brand" href="#">Navbar</a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="#">Home</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Link</a>
          </li>
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
              Dropdown
            </a>
            <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
              <li><a class="dropdown-item" href="#">Action</a></li>
              <li><a class="dropdown-item" href="#">Another action</a></li>
              <li><hr class="dropdown-divider"></li>
              <li><a class="dropdown-item" href="#">Something else here</a></li>
            </ul>
          </li>
          <li class="nav-item">
            <a class="nav-link disabled">Disabled</a>
          </li>
        </ul>
        <form class="d-flex">
          <input class="form-control me-2" id="search" type="search" placeholder="Search" aria-label="Search">
          <button class="btn btn-outline-success" type="submit">Search</button>
        </form>
      </div>
    </div>
  </nav>
  <div class="container my-3">
    <h1>Welcome to magic notes</h1>
    <div class="card" style="width: 18rem;">
      <div class="card-body">
        <h5 class="card-title">Add a note</h5>
        <div class="mb-3">
          <label for="exampleFormControlTextarea1" class="form-label">Example textarea</label>
          <textarea class="form-control" id="addTxt" rows="3"></textarea>
        </div>
        <button  class="btn btn-primary" id="addbtn">Add note</a>
      </div>
    </div>
    <h2>Notes</h2>
    <hr/>
    <div id="notes" class="row container-fluid">
    </div>
    <script src="app.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-W8fXfP3gkOKtndU4JGtKDvXbO53Wy8SZCQHczT5FMiiqmQfUpWbYdTil/SxwZgAN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-skAcpIdS7UcVUC05LJ9Dxay8AXcDYfBJqt1CJ85S/CFujBsIzCIv l9liuYLaMQ/" crossorigin="anonymous"></script>
</body>
</html>

CodePudding user response:

did you try .indexOf()?

arr.splice(arr.indexOf(ele), 1);
  • Related