尝试根据自定义字母对字符串数组进行排序.那里可能有一些不必要的代码,但这是将几个不同的迭代混为一谈.
我正在对第一个字母进行基本排序,如果那不起作用,我将调用深度排序函数并开始处理这些字母.但是结果仅按首字母排序,后一种排序似乎是任意的.
有什么帮助吗?
var wordArray = ['apple', 'abbot', 'aatrophy', 'banana', 'berry', 'cherrypie', 'cherry', 'candy', 'grapefruit', 'pear', 'pizza', 'zebra', 'cigarette', 'guitar'];
var wordToLetterArray = [];
// var sortingString = "kwfhjrsbdtqmxaopzvieulgcny";
var sortingString = "abcdefghijklmnopqrstuvwxyz";
var deepSort = function(wordArray1, wordArray2) {
var forLoopIterations = 0;
if (wordArray1 && wordArray2) {
if (wordArray1.length > wordArray2.length) {
forLoopIterations = wordArray2.length;
} else {
forLoopIterations = wordArray1.length;
}
for (var i = 0; i <= forLoopIterations; i++) {
if (sortingString.indexOf(wordArray1[i]) > sortingString.indexOf(wordArray2[i])) {
return -1;
} else if (sortingString.indexOf(wordArray1[i]) < sortingString.indexOf(wordArray2[i])) {
return 1
} else {
if (i >= forLoopIterations) {
if (wordArray1.length > wordArray2.length) {
return 1;
} else if (wordArray1.length < wordArray2.length) {
return -1
} else {
return 0
}
} else {
}
}
};
} else {
return 0;
}
}
var populateWordToLetterArray = function() {
for (var i = 0; i <= wordArray.length - 1; i++) {
wordToLetterArray.push([]);
for (var x = 0; x <= wordArray[i].length - 1; x++) {
wordToLetterArray[i].push(wordArray[i][x]);
};
};
sortWordArraybyFirstLetter();
}
var sortWordArraybyFirstLetter = function sortWordArraybyFirstLetter() {
wordArray.sort(function(a, b) {
var aIndex = sortingString.indexOf(a[0]);
var bIndex = sortingString.indexOf(b[0]);
if (aIndex > bIndex) {
return 1;
} else if (aIndex < bIndex) {
return -1;
} else {
return deepSort(wordToLetterArray[wordArray.indexOf(a)], wordToLetterArray[wordArray.indexOf(b)]);
}
})
}
populateWordToLetterArray();
console.log(wordArray);
console.log(wordToLetterArray);
解决方法:
创建一个将单词“翻译”为自定义字母的功能,然后通过比较单词的“翻译”对单词进行排序:
function translate(str, alphabet) {
var abc = "abcdefghijklmnopqrstuvwxyz";
return [].map.call(str, function(c) {
return alphabet[abc.indexOf(c)] || c;
}).join("");
}
var wordArray = ['apple', 'abbot', 'aatrophy', 'banana', 'berry', 'cherrypie', 'cherry', 'candy', 'grapefruit', 'pear', 'pizza', 'zebra', 'cigarette', 'guitar'];
var sortingString = "kwfhjrsbdtqmxaozpvieulgcny";
wordArray.sort(function(a, b) {
return translate(a, sortingString).localeCompare(translate(b, sortingString));
});
document.write(wordArray)
这并不是特别有效,但是有优化的空间.