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

Time:09-06

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 ?

CodePudding user response:

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]

CodePudding user response:

It's because you did the assignment.

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

Just need to write as below code.

this.selectedRoles.splice(0,1);

CodePudding user response:

As per the documentation Array.prototype.splice is an inplace function

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. 

And, this.selectedRoles.splice(0,1) returns the deleted item which you are assigning to this.selectedRoles.

Just avoid assigning splice to the array variable.

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

CodePudding user response:

I think you have misunderstood what splice does.

  1. The splice() method adds and/or removes array elements.
  2. The splice() method overwrites the original array.

Reference

this.selectedRoles.splice(0,1) would return the value at the index that is removed and not what is left inside the array, hence you are getting 1. Furthermore, you are assigning it to the same variable and thus overriding the old array with the removed values.

Return value of splice

An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

Reference

I think your requirement is to remove the first index if the length is greater than 1, in this case it is better to use slice instead of splice. slice does not alter the original array. It returns a shallow copy of elements from the original array. More information here.

  • Related