javascripttostringarray.prototype.map

How can I convert an array of numbers to strings?


I can't convert array's numbers into strings. What is wrong with my code?

I also tried: this.userIds.toString().split(',')

collectIds() {
  this.array.forEach((e, i) => {
    // [8, 8, 8, undefined, undefined, undefined]
    if (this.array[i].details.user_id !== undefined) {
      this.userIds.push(this.array[i].details.user_id)
      // [8, 8, 8]
    }
  });
  
  this.userIds.map(e => e.toString())
  console.log("userIds: ", this.userIds)
  // [8, 8, 8]
}


Solution

  • map creates a new array with the transformed elements. It does not modify the old one.

    You could reassign this.userIds to the new array.

    this.userIds = this.userIds.map(e => e.toString());
    

    Or you could use forEach and mutate the array while iterating.

    this.userIds.forEach((e, i, a) => a[i] = e.toString());