0

In my Class I declared an Array

myUsers = new Array();

Where I want to Add Usernames, unique. So i thought I would check if the ArrayLenght is 0, if yes, add a User. Which works fine. I if a Username wants to be added, which exists in the Array, it should be deleted. But this way, If I add one User the console says ["User1"] If I try to add another one (another one User2) the console says ["User1", empty] Can't get behind that...

isChecked(e) {
     var usersArray = this.myUsers;
     console.log(usersArray.length);


 if(this.myUsers.length == 0) {
      console.log("is 0");
      this.myUsers.push(e);
    } else {
      console.log("is not 0");
      for (var i= 0; i < this.myUsers.length; i++) {
        if (this.myUsers[i] == e) {
           console.log("is in array");
           delete this.myUsers[i];
          } else {
            this.myUsers.push(e);
          }
     }
  }

}

isherwood
  • 58,414
  • 16
  • 114
  • 157
parvaneh
  • 99
  • 1
  • 13
  • 1
    Consider using a `Set` instead of an array. – trincot Jan 23 '18 at 21:16
  • This seems to work. But, My Data is coming from a Form with Checkboxes. I want to delete the Name if the Checkbox is unchecked. That's why I wanted to delete a Name wich is in the Array. Why is Set better? – parvaneh Jan 23 '18 at 21:35
  • With Set it works fine. if(this.mySet.has(e)) { console.log("item in set"); this.mySet.delete(e); } else { this.mySet.add(e); } – parvaneh Jan 23 '18 at 21:43

2 Answers2

0

Replace delete this.myUsers[i]; with this.myUsers.splice(i, 1);

holtc
  • 1,780
  • 3
  • 16
  • 35
0

You don't want to delete the value. That will just clear the value. What you want instead is to truncate the array. To do that, use the splice() function:

this.myUsers.splice(i, 1);

The first parameter is the index to start deleting. The second is how many values to delete (in this case, 1). It mutates the actual array, so no need to assign it back or anything.

samanime
  • 25,408
  • 15
  • 90
  • 139
  • Okay, did that, but still not working... now it does not add another user at all after calling the function again. – parvaneh Jan 23 '18 at 21:20