JavaScript string de duplication

Posted by ocpaul20 on Tue, 31 Dec 2019 08:32:42 +0100

JavaScript string de duplication

Method: write on the prototype chain, use the characteristics that the attributes of the object cannot be the same to de duplicate, and add each character of the string as the attribute name of the object (an object cannot have two attributes with the same name).

Code implementation:

// Encapsulate a method in the prototype chain
String.prototype.unique = function () {
    var newStr = "",                             // Empty array
        newObj = {},                             // Empty object
        newLen = this.length;                    // Call string length
    for(var i = 0; i < newLen; i ++) {           // Traversal string
        if(!newObj[this[i]]) {                   // Judge whether there is this attribute in the object
            newObj[this[i]] = "Hello World!!!";  // Add attribute
            newStr += this[i];                   // String splicing
        }
    }
    return newStr;
}

Call this method:
Test with a super array

String.prototype.unique = function () {
    var newStr = "",                      
        newObj = {},                          
        newLen = this.length;                    
    for(var i = 0; i < newLen; i ++) {           
        if(!newObj[this[i]]) {                   
            newObj[this[i]] = "Hello World!!!";  
            newStr += this[i];                   
        }
    }
        return newStr;
var newStr = "qweqwrwirhrwiuqiqyqfskfhqiwfywsvuqfiuqgowhabsojhqoiwodqufwUGEFYW
UYYAUUUWGUIYADPYFAWYYWIOFYOIERYHJFDHFWOIEHFDJKOHiawieofhsjdfkhqoj
njvnmdxcbnvxmvnssfoiwuefdjhbfwueifgbhdbvwiueqfiwbdbvncmvxmvqiweqo
fqhoury12784y187t7w7193029187461827467185172483436377293701283104
41ri103284653y4t7854y823y7trgf3y4rgf783rfg43ff847f122378563421831
1=11=2u8e812ywuuhdq87y8e7y4827y82y810`2eu92re923ry23
`923y8r289eu2ioefh293hfebdsjfb823";
console.log(newStr.unique());

The result is:
Before lifting:

After weighing:

The above is the research on the string de duplication of javascript, which will be improved in the future.

Topics: Attribute Javascript