Home > Software design >  How to convert a string in array to number in Javascript?
How to convert a string in array to number in Javascript?

Time:04-20

Suppose that I need to convert the content of these arrays below to number

const a = ['1']

const b = ['1', '2', '3']

To do that, I have tried these methods below to no avail. The content of the arrays are still of string type.

Number(a)

b.map(Number)

I have searched in the documentary of Number and (for me) those methods should sufficient to do the job. Did I miss something in understanding how Number works or I simply used wrong solution for the problem?

CodePudding user response:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

So the solutions you need is:

const a = ['1']

const b = ['1', '2', '3']

const newA = a.map(Number);
const newB = b.map(Number);

console.log(newA) // [1]
console.log(newB) // [1, 2, 3]

As a map create a new array, variable a and b still got the same values.

CodePudding user response:

const b = ['1', '2', '3'];

const nums = b.map(Number)

const nums2 = b.map((num) =>  num)

console.log(nums, nums2)

CodePudding user response:

Use parseInt(), this will convert a string into it's corresponding integer value.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

CodePudding user response:

use this to convert array string to array number

a =  a.map(d => Number(d))
  • Related