gpt4 book ai didi

javascript - 通过自定义字母表javascript对字符串函数进行排序

转载 作者:行者123 更新时间:2023-11-29 10:41:15 24 4
gpt4 key购买 nike

尝试根据自定义字母表对字符串数组进行排序。可能其中有一些不必要的代码,但那是几个不同的迭代混合在一起的结果。

我正在对第一个字母进行基本排序,如果这不起作用,我将调用深度排序函数并开始对字母进行排序。但是结果只是按首字母排序,后面的排序就显得随意了。

有什么帮助吗?

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)

这不是特别有效,但仍有优化空间。

关于javascript - 通过自定义字母表javascript对字符串函数进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28711653/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com