Removal method: 1. Use toString() and split() methods to convert numbers into character arrays; 2. Use "[...new Set(arr)]" or "Array.from(new Set(arr))" statement repeats characters everywhere; 3. Convert the deduplicated array into numbers.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
JavaScript removes duplicate characters from numbers
In JavaScript, if you want to remove duplicate characters from numbers, you can use array deduplication. Method:
First convert the number into a character array;
then use Set to remove duplication from the array.
Convert array back to number.
Method to convert numbers into character arrays:
var num=12345654123; var str = num.toString(); var arr=str.split("");
Then use Set to deduplicate the array, there are two Method 1:
Method 1:
var newArr = [...new Set(arr)];
Method 2:
var newArr =Array.from(new Set(arr));
The output results are consistent:
Finally convert the array back to numbers
var str=newArr.join("") var newNum=Number(str);
[Related recommendations: javascript learning tutorial]
The above is the detailed content of How to remove repeated characters from numbers in JavaScript. For more information, please follow other related articles on the PHP Chinese website!