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

203
Visualizações
Javascript regex on array

I currently have this example array:

array = [1.2%, 16%, 9.0%, 8%]

I want to get the highest number so I did this:

Math.max.apply(null, array);

But it shows an error maybe because of the '%'

How can I filter the array using regex? It's my first time using regex on the array. I already spent more than 2 hours I still don't get it.

Here are my works that did not work:

array = [1.2%, 16%, 9.0%, 8%].match(/[0-9]*\.?[0-9]/);
array = [1.2%, 16%, 9.0%, 8%].replace(/[0-9]*\.?[0-9]/);
array = [1.2%, 16%, 9.0%, 8%].match(/[\d]+/);

Sorry I am new to javascript. Thanks.

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

0

You can map the strings to parseFloat, then the "%" will be ignored:

let array = ["1.2%", "16%", "9.0%", "8%"];

let result = Math.max(...array.map(parseFloat));

console.log(result);

NB: I used the spread syntax here instead of apply, just because that is the more modern way to write it (since EcmaScript 2015).

about 4 years ago · Juan Pablo Isaza Relatório

0

First of all, the % symbol isn't valid on a number, so you probably want to strip that first (your array elements will be strings, actually):

const array = ['1.2%', '16%', '9.0%', '8%'];
const floats = array.map(e => parseFloat(e.replace('%', ''));

Now you have an array of floating numbers, so you can now find out the biggest number:

const biggest = Math.max(...floats);
console.log(biggest);
about 4 years ago · Juan Pablo Isaza Relatório

0

You won't need regular expressions at all:

Math.max(...['1.2%', '16%', '9.0%', '8%'].map(e => parseFloat(e)).sort());
// or maybe add the '%' if that's what you're after
Math.max(...['1.2%', '16%', '9.0%', '8%'].map(e => parseFloat(e)).sort()) + '%';
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