0

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

3
  • 2
    Please add an array to the snippet demo above so we can see the output. Commented Jul 20, 2023 at 14:06
  • 2
    Your demo code has an error and there is no sample data Commented Jul 20, 2023 at 14:10
  • 2
    this.userIds = this.array.filter( x => x!== undefined).map(x => x.toString()); Commented Jul 20, 2023 at 14:13

2 Answers 2

1

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());
Sign up to request clarification or add additional context in comments.

1 Comment

I used forEach method, thank you!
0

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())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.