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

135
Visualizações
cannot return unique elements from matches

I want to return _1, _2 and not _1, _2, _1 :

let regex = /_[0-9]/g;
let string = 'a_1 b_2 c_1';
let matches = [...string.matchAll(regex)];
let unique = [...new Set(matches)];
alert(unique);

can't see why it doesn't remove duplicates ?

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

0

You're using .matchAll, which will return an iterator that, when turned into an array, results in:

[
  ['_1', index: 1, input: 'a_1 b_2 c_1', groups: undefined],
  ['_2', index: 5, input: 'a_1 b_2 c_1', groups: undefined],
  ['_1', index: 9, input: 'a_1 b_2 c_1', groups: undefined]
]

So, deduplicating the array items with a Set doesn't work - arrays are never === to each other.

Use .match instead of .matchAll so you get an array of matches (strings), not an array of arrays.

const regex = /_[0-9]/g;
const string = 'a_1 b_2 c_1';
const matches = string.match(regex);
const uniqueMatches = [...new Set(matches)];
console.log(uniqueMatches);

about 4 years ago · Juan Pablo Isaza Relatório

0

Without using a different method, matchAll might not be the best here, flatten the matches array before passing to the Set constructor:

let regex = /_[0-9]/g;
let string = 'a_1 b_2 c_1';
let matches = [...string.matchAll(regex)].flat();
let unique = [...new Set(matches)];

console.log(unique);

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