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



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() { => {
      if (element == '') {
        element.push('No 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?


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: = => d === '' ? 'No Data' : d);

What we’ve done here, is use 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() { = => d === '' ? 'No Data' : d);

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