SirNail
SirNail

Reputation: 95

Converting number string into number in an array

I have an array containing single strings. e.g. ["a", "b", "3", "c"]; However, I need any number in this array to be a number and not a string.

Result would be ["a", "b", 3, "c"]; so I could then run a regex and get all numbers out of the array.

Hope this is clear enough.

Upvotes: 0

Views: 117

Answers (2)

Emeeus
Emeeus

Reputation: 5260

You could use + since NaN is evaluated as false if the value is not a number, so (+e || e) returns a number or the original value:

const array = ["a", "b", "3", "c"];
const res = array.map(e=>(+e || e));

console.log(res);

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37775

You can use map and isNaN

let a = ["a", "b", "3", "c"];
let final = a.map(val => !isNaN(val) ? +val : val)
console.log(final)

Upvotes: 4

Related Questions