DEV Community

Cover image for Convert an array of strings to numbers
syedsimanta03
syedsimanta03

Posted on

Convert an array of strings to numbers

const toNumbers = arr => arr.map(Number);

// Or
const toNumbers = arr => arr.map(x => +x);

// Example
toNumbers(['2', '3', '4']);

// [2, 3, 4]

Top comments (2)

Collapse
 
itachiuchiha profile image
Itachi Uchiha

You'll get NaN in following scenarios:

Empty string -> ''

String with space ' '

function definition => () => {}

undefined value => undefined

null value => null

Collapse
 
syedsimanta03 profile image
syedsimanta03

we can use ts or input validation when writing any function