Why Splice removes only last element when array elements are the same

Go to this StackBlitz Link (Not Working)

Go to this StackBlitz Link (Working Fine)

My question is about Array.splice.
Array.splice is working fine when array data are different but when data of array are of the same kind, Array.splice removes only the last index. In this case, splice ignores provided index to remove element from array.

Both example has common HTML Template

<div class="container">
    <table class="table table-dark table-striped table-hover">
               <td scope="col"> Index </td>
               <td scope="col"> Value </td>
               <td scope="col"> Action </td>
            <tr *ngFor="let row of rows; let i = index"  [@itemAnim]>
                <td> {{i}} </td>
                <td><button class="btn btn-danger" (click)="deleteRow(i)">Delete</button></td>
    <button class="btn btn-primary " (click)="addRow()">Add row</button>

See this example working as expected:

index = 1;
rows = [1]; 

addRow() {   
   this.rows.length > 0 ?  this.index ++ : this.index = 1;

deleteRow(row: number) {
   return this.rows.length > 0 ? this.rows.splice(row, 1) : this.index = 1;

And this is not working:

rows = [1]; 

addRow() {   

deleteRow(row: number) {
   this.rows.splice(row, 1) ;

In the above code, I am pushing only 1 when addButton is clicked. And deleting button only deletes from the last index instead of providing row number index though.

My question is why this is happening? The above stackBlitz link shows about same ambiguity.

42 thoughts on “Why Splice removes only last element when array elements are the same”

Leave a Comment