skip to Main Content

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

2

Answers


  1. Array.prototype.map() returns a new array.

    You will need to reassign this.userIds if this is your intention.

    this.userIds = this.userIds.map(e => e.toString())
    
    Login or Signup to reply.
  2. 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());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search