1

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>

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

A final note: in case the changes aren't picked up, try: this.existingSavings = [...this.existingSavings.filter(s => whatever you put here)]. This creates a new array and changes the reference of this.existingSavings and is more likely to be picked up by Angular's change detection.
1

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;
}

Comments

0

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;
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.