0

I have an array of values such that arr = [108, 109]. I then converted them to a string using arr.toString(), thus getting "108, 109". The reason I did this was because my API required that this parameter arr asked for an array to string conversion. How can I turn this value into an integer?

I tried doing const test = parseInt(arr) but I only get 108. Why is that? I essentially just want the values 108, 109.

atiyar
  • 7,762
  • 6
  • 34
  • 75
Michael Lee
  • 327
  • 2
  • 5
  • 18
  • This is about why - [link](https://stackoverflow.com/questions/11340673/why-does-parseint1-0-19-return-18) – hyojoon Dec 18 '20 at 08:38

3 Answers3

1

First split the values with comma using the split() method like this.

arr.split(',')

After that you will get each value separated in an array which will be accessible by giving array index. So arr[0] will include 108 and arr[1] will include 109. Now all that's left to do is parse them individually.

parseInt(arr[0]) 
parseInt(arr[1]) 
Mr Khan
  • 2,139
  • 1
  • 7
  • 22
1

The reason you are getting 108 is due to parseInt() stopping after any invalid outcome. So what you are basically trying to to is:

parseInt('108, 109');

which stops at the comma.

In case you need the whole array I suggest using split() together with map().

const test = '108, 109'.split(',').map(Number);
console.log(test)
JavaScript
  • 539
  • 2
  • 10
0

the values 108 and 109 are different, so you have to parseInt them separately by doing parseInt("108") and parseInt("109")

Manu Sampablo
  • 350
  • 5
  • 17