'Splicing objects from an array Javascript

I am trying to remove an object from an array if a particular value for a key matches a given string:

Example data:

array = [{_id: "abc", test: "123"}, 
         {_id: "def", test: "123"},
         {_id: "ghi", test: "123"}];

Here is my loop:

for (var i = 0; i < array.length; i++) {
    var x = "123"
    if (array[i].test == x) {
       array.splice(i, 1)
    }
}

This should return an empty array but it's leaving one object in the array (the last one) and I've got no clue why.



Solution 1:[1]

You must not increment i if you remove an element.

Suppose the array has two matching elements.

The first iteration, i = 0

i ==>>  element 1
        element 2

You then remove element 1, and increment i

        element 2
i ==>>   

There are many ways you can correct this. Here's an example that replaces your for loop with a while loop.

var i = 0;
while (i < array.length) {
    var x = "123"
    if (array[i].test == x) {
       array.splice(i, 1)
    } else {
       ++i;
    }
}

Solution 2:[2]

Figured it out:

array = array.filter(function(array) {
  var x = "123";
  return array.test !== x;
})

Solution 3:[3]

array = [
  {id: "abc", test: "123"}, 
  {id: "def", test: "456"},
  {id: "ghi", test: "789"}
];
let x = "123";
let i = array.findIndex(data => data.test === x);
    if (i !== -1) {
        array.splice(i, 1);
    } else ...
console.log(array);

Solution 4:[4]

I have written a function that takes the index and event values from the html and processes in ts

app.component.html

<tr *ngFor="let container of containers; let i = index;" 
      [(ngModel)]="miningname"
            ngDefaultControl>
              <td>
    <input *ngIf="addMore" type="text" class = "form-control" 
     placeholder="Key" 
     [(ngModel)]="container.key2Name" 
       (ngModelChange)="textKeyChangedMore($event,i)">
</td></tr>

app.component.ts

  textKeyChangedMore(eventMore, indexMore) {


    var valueLength = this.selectedAPIName.length

      var i = indexMore+1;
      if (this.selectedAPIName[i].value == undefined ) {

        this.selectedAPIName.splice(indexMore + 1, 1, { key: eventMore, value: undefined });
      }
      else if (this.selectedAPIName[i].value !== undefined) {

        this.selectedAPIName.splice(indexMore + 1, 1, { key: eventMore, value: this.selectedAPIName[i].value });
      }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrew Shepherd
Solution 2 Adam Moisa
Solution 3 Maria Gabriela Alarcon
Solution 4 Techdive