Skip to main content

Posts

Showing posts with the label parse string as integers

Safe way to converting array of strings as Integers in javascript

The Problem This is a very short post on how to be very careful when converting a collection (array) of strings to integers Let us assume that we receive from an API call or from some other source a collection of numbers in string format Example ["1","9","2"] In this case we might be planning to use the map function along with the parseInt to get the job done as given below ["1","9","2"].map(parseInt) However, the catch here is that the above method will return the below response (3) [1, NaN, NaN] This will be a lot confusing to many because the first number gets parsed and the remaining ones does not. Let us consider another example ["10","10","10","10"].map(parseInt) This results in a similar output where the developer might get even puzzled [10, NaN, 2, 3] This looks like the last 2 numbers are getting printed like their i