This article mainly introduces how to use JavaScript to find strings in different order in arrays. This article uses two methods to solve this algorithm problem. If you need it, refer to the following requirements: find the array elements of a string in different order from a group of arrays. Suppose there is an array like this:
The Code is as follows:
['Abc', 'Hello', 'bdca', 'olleh', 'cadb', 'nba ', 'abn', 'abc']
The result is as follows:
The Code is as follows:
['Abcd', 'bdca', 'cadb']
The key point here is to determine whether a set of strings are only in different character order, as long as the entire key point is solved.
Method 1:
The Code 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 a single character to Unicode encoding
// Obtain 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
// Appear in another string to avoid the following situations
// ['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 a string and converts a single character to Unicode encoding. The encoding is obtained and calculated. The encoding of abcd and bdca is consistent. Finally, the encoding and the object key are used to save the encoded and consistent strings.
Method 1 It should be noted that the Unicode encoding of the string "ad" and "bc" is the same, and an additional judgment is required at this time, check whether the first character in any string has appeared in another string.
Method 2:
The Code 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 by sort. After using sort for abcd and bdca, it will become abcd, the sorted string is used as the object key to save the sorted string.
In fact, the principle of the two methods is to convert characters to Unicode encoding, but method 1 is an explicit conversion, and the sort sorting used in method 2 is implicitly converted.