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

Time:12-28

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?

CodePudding user response:

let list = this.data.map(d => d === '' ? 'No data' : d)

CodePudding user response:

Because element is a string while push function is only supported for array. Just return 'No data' in case element is empty string:

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

onClick() {
    this.data = this.data.map(v => v || 'No Data');
    console.log(this.data);
  }

CodePudding user response:

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 do here, is use 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);
} 

CodePudding user response:

element is the string you can't push, use array.map to solve this

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

onClick() {
   const list = this.data.map(element => {
      if (element === '') {
        return 'No Data';
      }
      return element;
    });
    console.log(list);
  }

CodePudding user response:

You could map the array with replacements.

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

data = data.map(v => v || 'No Data');

console.log(data);

CodePudding user response:

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

var dataArray = new Array();

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

CodePudding user response:

When you use for or for each loop so that particular element is a string, not an array that why its shows element.push is not a function.

to change element of an array you can use this method

 data = ['a', 'b', '', 'd', 'e'];
    for (var i = 0; i < data.length; i  ){
        if (data[i] == '')
            data[i] = 'No Data';}
    console.log(data)
  • Related