Home > Web Front-end > JS Tutorial > body text

How to remove repeated characters from numbers in JavaScript

青灯夜游
Release: 2022-01-26 12:06:25
Original
2910 people have browsed it

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

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)];
Copy after login

Method 2:

var newArr =Array.from(new Set(arr));
Copy after login

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!