javascriptangulartypescriptarray-splice

Why the Splice function deletes the item at the index 1 when I am asking it to delete at index 0?


selectedRoles= [1,230] 
if(this.selectedRoles.length > 1) 
      {
        this.selectedRoles= this.selectedRoles.splice(0,1);
        
      }

I am trying to delete item at index 0 which is 1 but instead it deletes the item at index 1 which is 230.

Why ?


Solution

  • Because you assigned the output of splice function, which is [1] back to the original this.selectedRoles:

    this.selectedRoles = this.selectedRoles.splice(0,1);
    

    All you had to do is to remove the assignment, e.g.:

    this.selectedRoles.splice(0,1);
    this.selectedRoles // would be [230]