我正在尝试编写一个简单的意大利语词典。我希望能够按字符串的部分排序。我将意大利语,英语和信息结合在一起。这是完整代码的链接:https://www.codepile.net/pile/dJe80d7m
我用“:”字符将它们分开。这样,我可以在意大利语区域使用“ Ghiaccio”,在英语区域使用“ Ice”,在信息区域使用“(singular,m)”。当我尝试使用这种方法进行排序时,翻译会变得混乱。
word_bank = [
"Animale:Animal:(singular, m)",
"Animali:Animal:(plural, m)",
"Libro:Book:(singular, m)",
"Libri:Books:(plural, m)",
"Zucca:Pumpkin:(singular, f)",
"Zucce:Pumpkins:(plural, f)",
]
word_bank.sort()
答案 0 :(得分:0)
这是解决您问题的方法:
const word_bank = [
"kucce:Pumpkins:(plural, f)",
"Zucca:Pumpkin:(singular, f)",
"Animale:Animal:(singular, m)",
"Libro:Book:(singular, m)",
"Libri:Books:(plural, m)",
"Animali:Animal:(plural, m)",
];
const sortByLanguage = (arr, sortBy) => {
if(['italian', 'english'].indexOf(sortBy) === -1) {
throw new Error("Invalid Enum Value For 'sortBy'.");
} else {
const index = (sortBy === 'italian') ? 0 : 1;
const splittedArray = arr.map(a => a.split(':'));
const sortedSplittedArray = sortSplittedArray(splittedArray, index);
const sortedByLanguage = sortedSplittedArray.map(x => x.join(':'));
return sortedByLanguage;
}
}
const sortSplittedArray = (arrToSort, index) => {
arrToSort.sort((a, b) => {
if (a[index].toLowerCase() < b[index].toLowerCase()) return -1;
if (a[index].toLowerCase() > b[index].toLowerCase()) return 1;
return 0;
});
return arrToSort;
}
const sortedByEnglish = sortByLanguage(word_bank, 'english');
const sortedByItalian = sortByLanguage(word_bank, 'italian');
console.log('Sorted By English Is: => ', sortedByEnglish);
console.log('Sorted By Italian Is: => ', sortedByItalian);
注意:如果要区分大小写,可以从 sortSplittedArray()方法中删除 toLowerCase()。
希望这会有所帮助:)
答案 1 :(得分:-2)
可能不是一个完整的答案。但是请尝试使用localeCompare并对其余部分进行排序。
word_bank = [
"Animale:Animal:(singular, m)",
"Animali:Animal:(plural, m)",
"Libro:Book:(singular, m)",
"Libri:Books:(plural, m)",
"Zucca:Pumpkin:(singular, f)",
"Zucce:Pumpkins:(plural, f)",
]
word_bank.sort((a,b) => {
console.log(a,b);
console.log(a.localeCompare(b));
});