Requirements Description: Finds a set of array elements from a set of arrays in a different order of strings. If there is such an array:
The code is as follows:
[' ABCD ', ' hello ', ' bdca ', ' Olleh ', ' cadb ', ' NBA ', ' ABN ', ' ABC ']
The results to be found are:
The code is as follows:
[' ABCD ', ' BDCA ', ' cadb ']
The key point here is to determine whether a set of strings is just a different sequence of characters, as long as the whole point is resolved.
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;
Converts a single character to Unicode encoding
To take and compute 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
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 employs every character in the string, and then converts a single character to Unicode encoding, which computes the encoding and the ABCD and BDCA coding will be consistent. Finally, the encoding and the key of the object are used to save the coded and consistent strings.
Method 1 Note that the Unicode encoding of the string "ad" and "BC" is the same, and at this point you need to add a judgment that detects whether the first character in any string appears 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 Converts a string to an array and then sorts the arrays, and ABCD and BDCA use sort to become ABCD, and the snapped string is used as the key of the object to hold the sorted string.
In fact, the principle of both methods is to convert characters to Unicode encoding, but Method 1 is an explicit conversion, and the sort order used in Method 2 is implicitly converted.