I am trying to convert an array of numbers (represented as strings) to an array of numbers.
Here is an example array: [ '39.4K', '83.4K', '1.5M', '111.3K', '5878' ]
; the numbers may have the conventional "K" and "M" suffixes, denoting factors of 1000 and 1000000, respectively. The desired output of the previous example is [39400, 83400, 1500000, 111300, 5878]
.
Here is what I have so far:
var sample = [ '39.4K', '83.4K', '1.5M', '111.3K', '5878' ]
function convert(arr) {
var conversions = {'K':1000, 'M':1000000}
var result = []
for (entry of arr) {
var sep = entry.split(/(?=[A-Z])/)
if (sep.length == 1) {
result.push(parseFloat(sep[0]))
} else {
var number = parseFloat(sep[0]) * conversions[sep[1]]
result.push(number)
}
}
return result
}
console.log(convert(sample))
I think this works, but are there any ways to improve my code? I would have assumed JS has something to automatically convert different representations of numbers. Any advice or suggestions (using only vanilla JS) greatly appreciated.