Requirement Description: Find an array element of a set of strings arranged in different orders from a set of arrays. If there is an array like this:
The code copy is as follows:
[ 'abcd', 'hello', 'bdca', 'olleh', 'cadb', 'nba', 'abn', 'abc' ]
The results to be found are:
The code copy is as follows:
[ 'abcd', 'bdca', 'cadb' ]
Then the key point here is to determine whether a set of strings is just a different order of characters. As long as the entire key point is solved, it will be easier to do.
Method 1:
The code copy is as follows:
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;
// Convert single characters into Unicode encoding
// Fetch and calculate the encoding
for( j = 0; j < strLength; j++ ){
num += item.charCodeAt( j);
}
if( !firstItem ){
firstItem = item;
obj[ num ].push( item );
}
// Check whether the first character of the string to be added is whether the
// Appear in another string to avoid the following
// [ 'ad', 'da', 'bc' ]
else if( ~firstItem.indexOf(item.charAt(0)) ){
obj[ num ].push( item );
}
}
for( name in obj ){
console.log( obj[name] );
}
};
Method 1 uses traversing each character in the string, and then converting a single character into Unicode encoding, and performing summation of the encodings. The encoding sums of abcd and bdca will be consistent. Finally, use the encoded and key as the object to save the encoded and consistent string.
Method 1 It should be noted that the Unicode encoding of the string "ad" and "bc" is the same. At this time, you need to add an additional judgment to detect whether the first character in any string has appeared in another string.
Method 2:
The code copy is as follows:
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. Abcd and bdca will become abcd after sorting it with sort. Use the well-ordered string as the key of the object to save the consistently sorted string.
In fact, the principle of the two methods is to convert characters into Unicode encoding. However, method 1 is an explicit conversion, while the sort sort used in method 2 will be implicitly converted.