RRB
RRB

Reputation: 2116

Check and remove null values in array

I have an array that I am trying to check for null values. If there are any, I would like to remove them from the array. Here is my code and attempt.

this.existingSavings = [{
    value: null,
    sourceId: null,
    fund: null
}];

changeSavingsAmount(): void {
    for(let i = 0; i < this.existingSavings.length; i++) {
      if(this.existingSavings[i].value == null) {
        //not sure what to do here
      }
    }
}

<div *ngFor="let source of existingSavings; let i = index;" class="row">
   <div class="col-4">
     <div class="input-container">
        <label for="savings">Existing savings value</label>
        <input id="savings" [(ngModel)]="existingSavings[i].value" (blur)="changeSavingsAmount()" type="number"
          placeholder="R">
     </div>
   </div>
</div>

Upvotes: 1

Views: 1299

Answers (3)

Hasitha Amarathunga
Hasitha Amarathunga

Reputation: 2005

You can also check it using forEach and ignore the null items as below.

changeSavingsAmount(): void {
    const existingSavings = [];
    this.existingSavings.forEach(exSave => {
      if (exSave[i].value != null) {
         existingSavings.push(exSave);
      }
    });
    this.existingSavings = existingSavings;
}

Upvotes: 1

kushal shah
kushal shah

Reputation: 863

solution using splice

in your ts file

existingSavings = [
    {
      value: null,
      sourceId: null,
      fund: null
    },
    {
      value: "f",
      sourceId: "dd",
      fund: null
    },
    {
      value: 't',
      sourceId: 'uu',
      fund: null
    }
  ];
  constructor() {
    var d = this.removeByAttr(this.existingSavings, "value", null);
    console.log(d);
  }
  removeByAttr(arr: any, attr: any, value: any) {
    var i = arr.length;
    while (i--) {
      if (
        arr[i] &&
        arr[i].hasOwnProperty(attr) &&
        (arguments.length > 2 && arr[i][attr] === value)
      ) {
        arr.splice(i, 1);
      }
    }
    return arr;
  }

Upvotes: 0

igg
igg

Reputation: 2250

If you only want to check the value property, you can use filter:

changeSavingsAmount(): void {
    this.existingSavings = this.existingSavings.filter(s => s.value != null);
}

Just be careful, as this is only checking the value property of each element in your array of object. The other two properties aren't checked, and neither is the element itself. You could do that with:

filter(s => s != null && s.value != null && s.sourceId != null && s.fund != null);

Upvotes: 1

Related Questions