0

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.

2 Answers 2

4

You can use map and isNaN

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

Sign up to request clarification or add additional context in comments.

1 Comment

@Tony you can accept an answer by clicking on the grey checkmark on the left (You get 2 reps as well)
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.