How to push data in empty space in array using foreach loop?

0

Issue

I have this below code where in I am trying to push ‘No Data’ in one of the index in array which doesn’t have data.

data = ['a', 'b', '', 'd', 'e'];

onClick() {
    this.data.forEach(element => {
      if (element == '') {
        element.push('No Data');
      }
    });
    console.log(this.data);
  }

But I am getting error as TypeError: element.push is not a function.

What is wrong in the code and is there any better ways to solve this?

Solution

Each element of your array is a string.

Strings don’t have a push method and they cannot because they are immutable. That is you can’t change the characters in a string.

This is trivially solved however, as follows:

this.data = this.data.map(d => d === '' ? 'No Data' : d);

What we’ve done here, is use Array.prototype.map to transform the array into a new array with all of the empty string elements replaced as per your specifications.

In context:

data = ['a', 'b', '', 'd', 'e'];

onClick() {
  this.data = this.data.map(d => d === '' ? 'No Data' : d);
  console.log(this.data);
} 

Answered By – Aluan Haddad

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More