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 ?
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);
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);