Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

191
Visualizações
Convert array of strings to array of numbers?

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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

When turning one array into another by transforming each element, .map is the appropriate approach. Rather than parseFloat(sep[0]), consider destructuring the split result and conditionally multiplying with the conversions value for a more concise approach.

const sample = [ '39.4K', '83.4K', '1.5M', '111.3K', '5878' ]
const conversions = {'K': 1e3, 'M': 1e6};

const convert = arr => arr.map((str) => {
  const [numPart, suffix] = str.split(/(?=[A-Z])/);
  return numPart * (suffix ? conversions[suffix] : 1);
});

console.log(convert(sample))

about 4 years ago · Juan Pablo Isaza Relatório

0

You could map the results and take the unit from object or one after splitting.

function convert(array) {
    const conversions = { K: 1000, M: 1000000 };
    return array.map(s => {
        const [v, u] = s.split(/(?=[KM]$)/);
        return v * (conversions[u] || 1);
    });
}

console.log(convert(['39.4K', '83.4K', '1.5M', '111.3K', '5878']))

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda