I have a string arrays like ['2022/10', '2021/05', '2022/01']
, ['John','Olivia','Adam']
, ['1.23','2.34','101']
in the same table. I want to convert those items of arrays to number but only if the item can be converted to number. For above example only ['1.23','2.34','101']
can be converted and other should be same. I tried to combine common methods like isNaN
and parseFloat
but couldn't manage. Because when I try to convert, it always gives NaN if the array can' be converted
Asked
Active
Viewed 130 times
0

seniorlearner
- 25
- 6
-
Are you checking if all of the array members are numbers or just filter out the array members that are not number ? – jeremynac Sep 30 '22 at 09:34
-
If you had ['John','Olivia','Adam', '1'], should it return ['1']? – jeremynac Sep 30 '22 at 09:34
1 Answers
0
I hope this snippet does what you want to, or it will lead you towards the solution.
const input = [['2022/10', '2021/05', '2022/01'], ['John','Olivia','Adam'], ['1.23','2.34','101']]
const converted = input.map(array =>
isNaN(array[0]) ? array : array.map(number => parseFloat(number))
)
console.log(converted)
Alternatively, you can make it more general, so every term will get turned into a number even in array like ['John','2.4','2022/10']
:
const input = [['2022/10', '2021/05', '2022/01'], ['John','Olivia','Adam'], ['1.23','2.34','101']]
const converted = input.map(array =>
array.map(
numberOrNotNumber => isNaN(numberOrNotNumber) ? numberOrNotNumber : parseFloat(numberOrNotNumber)
)
)
console.log(converted)

deaponn
- 837
- 2
- 12