Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

131
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda