Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!