Home  >  Article  >  Web Front-end  >  How to remove repeated characters from numbers in JavaScript

How to remove repeated characters from numbers in JavaScript

青灯夜游
青灯夜游Original
2022-01-26 12:06:252931browse

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.

How to remove repeated characters from numbers in JavaScript

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("");

How to remove repeated characters from numbers in JavaScript

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:

How to remove repeated characters from numbers in JavaScript

Finally convert the array back to numbers

var str=newArr.join("")
var newNum=Number(str);

How to remove repeated characters from numbers in JavaScript

[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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn