function unique_char(string) {
return String.prototype.concat(...new Set(string));
}
console.log(unique_char("Hellooooooooooooo"));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Can anyone help me understand how .concat a new Set will return unique characters ? I thought .concat will add , and why is there a spread operating ... before new Set?
CodePudding user response:
1)
new Set(string)
As strings
in JS are iterable so Set
will take string as an input and gives you set of unique characters.
2)
String.prototype.concat(...new Set(string)
The concat() method concatenates the string
arguments
to the calling string and returns a new string..One or more strings
to concatenate to str. - MDN
So concat
will take character by character and append
it into a single string
Have a look at the output of the following function
function unique_char(string) {
const set = new Set(string);
console.log(...set);
return String.prototype.concat(...set);
}
console.log(unique_char("Hellooooooooooooo"));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
So lets cut this command in the single pices:
new Set(string)
=> this will create a new Set from the string and leave every char only once- the
...
is used to "convert" the Set to an array (the set is iterable) - the
String.prototype.concat
is used to concat all characters from the array that was returned by the spread operator.