0

here is my first question: i build project "to do list", each time when i add task i push to array object. i would like to know how can i remove specific object from array "on-click".

*this is not the original project just example for know

 
const input = document.querySelector(".input");
    const maindiv = document.querySelector(".maindiv");
    
    const list = []
    
    input.addEventListener("keydown", function (e) {
        if (input.value && e.keyCode == 13) {
            const div = document.createElement("div")
            const title = document.createElement("h1")
            const btn = document.createElement("button")
    
            title.textContent = input.value
            btn.textContent = "remove"
    
            list.push({ text: input.value })
            btn.addEventListener("click", function (e) {
                for(let i = 0; i < list.length;i++){
                    if(list[i].num == i){
                        list.splice(i,1)
    
                    }
                }
                e.target.parentElement.remove()
            })
            div.appendChild(title)
            div.appendChild(btn)
            maindiv.appendChild(div)
            document.body.appendChild(maindiv)    
        }
    })
<html>
 <body>
    <input type="text" name="" class="input">
    <div class="maindiv"></div> 
    <script src="json.js"></script>   
  </body>
</html>

Then when i have few div(array.object) i would like to remove exactly object from array on click.

simo54
  • 218
  • 5
  • 16
  • 1
    Does this answer your question? [How can I remove a specific item from an array?](https://stackoverflow.com/questions/5767325/how-can-i-remove-a-specific-item-from-an-array) – A. Meshu Nov 01 '21 at 19:20

1 Answers1

0

You can use Array.splice to remove from the array at the index.

You can get the index using Array.findIndex

The example below is basic but should point you in the right direction. We start with an array of 10 values and use findIndex to get the index of the array value of i-5. Then, we use splice to remove it.

With your code, you could search on the text property of the object you are pushing to the array, or you could add some other identifier to make it easier to search.

const arr = []

for (let i = 0; i < 10; i++) {
  arr.push(`i-${i}`)
}

console.log(arr)

const index = arr.findIndex((a) => a === 'i-5')

if (index > -1) { // we found it
  arr.splice(index, 1)
}

console.log(arr)
Cjmarkham
  • 9,484
  • 5
  • 48
  • 81