0

I have a ToDo list, using localStorage... I need to be able to remove the item from the ToDo list... I try to use "dataArray.splice();" But the problem is I don't know how i can remove the object when the position is unknown...

function getTodoItems() {
    for (var i = 0; i < dataArray.length; i++) {
        if (!dataArray[i].listItem.length) return;
        var itemList = document.getElementById("my-todo-list");
        var list = document.createElement("li");
        itemList.appendChild(list);
        list.innerHTML = dataArray[i].listItem;
        var spanItem = document.createElement('span');
        spanItem.style.float = 'right';
        var myCloseSymbol = document.createTextNode('\u00D7');
        spanItem.classList.add("closeBtn");
        spanItem.appendChild(myCloseSymbol);
        listItems[i].appendChild(spanItem);
        close[i].onclick = function() {
            var div = this.parentElement;
            div.style.display = "none";
            console.log(dataArray);
        }
        var list = document.getElementsByTagName('li');
        list[i].onclick = function() {
            this.classList.toggle("checked");
        }
    }
}

3 Answers3

1

Then probably get its position:

 const position = dataArray.indexOf(/*whatever*/);
 dataArray.splice(position, 1);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

You can get the position of the element using 'indexOf' let pos = dataArray.indexOf(element); dataArray.splice(pos,1)

0

IndexOf() wont work if you are trying to find the index of an entire object or array inside the array.

If you need to find the index of an entire object inside your array, you test each one's value to find out if it is the correct one. I would use findIndex();

Try this in your console:

var array = []; 
for (var i = 0; i < 10; i++ ){ array.push({item: i}) }
console.log('Current Array: ', array); 

var indexOfResult = array.indexOf({item: 3});
console.log('indexOf result: ',indexOfResult);

var findIndexResult = array.findIndex(object => object.item === 3);
console.log('findIndex result: ',findIndexResult)
TJBlackman
  • 1,895
  • 3
  • 20
  • 46
  • Thanks, but when using indexOf dont i then already know the position? – Thomas Hermansen Dec 30 '17 at 19:23
  • IndexOf only works on primitive data types. Since I know that you are trying to find the index of an object, I know you need to use findIndex(). Read this: https://stackoverflow.com/questions/41443029/difference-between-indexof-and-findindex-function-of-array – TJBlackman Dec 30 '17 at 19:33
  • I just tried it out and it works almost, but now it is removing the first element still not the chosen – Thomas Hermansen Dec 30 '17 at 19:47