The JavaScript implementation looks up strings in an array in different order

  • 2020-03-30 04:01:32
  • OfStack

Requirement description: find a set of array elements of strings in a different order from a set of arrays. Suppose you have an array like this:


[ 'abcd', 'hello', 'bdca', 'olleh', 'cadb', 'nba', 'abn', 'abc' ]

The results to be found are:


[ 'abcd', 'bdca', 'cadb' ]

So the key point here is to determine whether a set of strings is just a different order of characters, as long as you solve for the whole key and everything else is fine.

Method 1:


var stringClassify = function( arr ){
    var arrLength = arr.length,
        obj = {},
        i = 0,
        num, item, name, firstItem, strLength;
 
    for( ; i < arrLength; i++ ){
        item = arr[i];
        strLength = item.length;
        num = 0;
 
        //Converts a single character to the Unicode encoding
        //Take and calculate the code
        for( j = 0; j < strLength; j++ ){
            num += item.charCodeAt( j );
        }     
 
        if( !firstItem ){
            firstItem = item;
            obj[ num ].push( item );
        }
                //By detecting whether the first character of the string to be added is
                //Occurs in another string to avoid
                // [ 'ad', 'da', 'bc' ]
        else if( ~firstItem.indexOf(item.charAt(0)) ){
            obj[ num ].push( item );
        }
    }
 
    for( name in obj ){
        console.log( obj[name] );
    }
};

Method 1 traverses each character in the string, then converts the individual character into Unicode encoding, and computes the sum of the encoding. The sum of the encoding of abcd and bdca will be the same. Finally, the encoded and consistent strings are stored with the encoding and the key as the object.

Method 1 is to note that the Unicode encoding for the strings "AD" and "BC" is the same, so you need to make an additional determination to detect whether the first character in any string appears in another string.

Method 2:


var stringClassify = function(){
    var arrLength = arr.length,
        obj = {},
        i = 0,
        num, item, name, strArr, newStr;
 
    for( ; i < arrLength; i++ ){
        item = arr[i];
 
        strArr = arr[i].split( '' );
        strArr.sort();
        newStr = strArr.join( '' );
 
        if( !obj[newStr] ){
            obj[ newStr ] = [];
        }
 
        obj[ newStr ].push( item );
    }
 
    for( name in obj ){
        console.log( obj[name] );
    }
};

Method 2 is to convert the string into an array and then sort the array. After using sort, abcd and bdca will become abcd. The ordered string will be used as the key of the object to save the string with the same sort.

In fact, the principle of both methods is to convert characters to Unicode encoding, except that method 1 is an explicit conversion, while the sort sort used in method 2 is an implicit conversion.


Related articles: