Skip to content
Advertisement

Array how to convert string to numbers except the operators

I have tried to convert the string type to numbers in array but the operators are in the way.

let outputArray = ['3', '5', '7' ,'+', '*', '9', '-' ];
numoutputArray = outputArray.map(Number);
console.log(numoutputArray)
//[ 3, 5, 7, NaN, NaN, 9, NaN ]

I wanted to get the array as [3,5,7,'+','*',9,'-'].

Advertisement

Answer

this way…

let outputArray = ['3', '5', '7' ,'+', '*', '9', '-' ]

numoutputArray = outputArray.map(v=>isNaN(v)?v:Number(v))

console.log( JSON.stringify( numoutputArray ))
 
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement