I have this code in TS
const arr = ["123.2", "abc", "78.3"]; console.log(arr.map((v) => (!isNaN(v) ? Math.floor(v) : v)));
but it gave warning because "abc" is string and isNaN and Math expect number, in this case what should I do? I know doing (v:any) will solve the issue but I'm looking for better solution.
(v:any)
demo https://codesandbox.io/s/practical-burnell-j3nyc?file=/src/index.ts:205-306
You can use + before each element to convert to numbers and then perform a check:
+
const arr = ["123.2", "abc", "78"]; console.log(arr.map(el => isNaN(+el) ? el : +el))
2.1m questions
2.1m answers
63 comments
56.6k users