0

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

1 Answers1

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