【发布时间】:2021-08-06 23:52:40
【问题描述】:
我的问题
如何在 Javascript 中按另一个字符串数组对字符串数组进行排序?
背景
我正在寻找一种通过另一个数组对字符串数组进行排序的方法。具体来说,我有一个问题,我无法按字母或数字排序。我知道 Javascript 支持自定义排序功能,如下例所示:
let numberArray = [40, 1, 5, 200];
function compareNumbers(a, b) {
return a - b;
}
numberArray.sort(compareNumbers);
我不确定自定义字符串比较函数如何解决我正在查看的问题。我在下面的第 1 部分和第 2 部分中给出了两个示例数组。如果您需要进一步说明,请询问。
第 1 部分
示例数组:请注意,educationSorted 是通过educationLevel 对education 进行排序的期望结果。
let education = [
"High School",
"Middle School",
"Undergrad",
"Middle School",
"Middle School",
"Middle School",
"Middle School",
"Graduate",
"Elementary",
"Elementary",
"Elementary",
"Elementary"
];
let educationLevel = ["Elementary", "Middle School", "High School", "Undergrad", "Graduate"];
let educationSorted = [
"Elementary",
"Elementary",
"Elementary",
"Elementary",
"Middle School",
"Middle School",
"Middle School",
"Middle School",
"Middle School",
"High School",
"Undergrad",
"Graduate"
];
第 2 部分
同样的一般问题,但字符串数组被数组数组替换。
let education = [
["Bob", "High School"],
["Alice", "Middle School"],
["Jane Doe", "Undergrad"],
["alex", "Middle School"],
["Mega Alice", "Middle School"],
["Jhon Doe", "Middle School"],
["Minor Bob", "Middle School"],
["Chicken", "Graduate"],
["Minor Chicken", "Elementary"],
["Clones", "Elementary"],
["Clones", "Elementary"],
["Clones", "Elementary"]
];
let educationLevel = ["Elementary", "Middle School", "High School", "Undergrad", "Graduate"];
let education = [
["Clones", "Elementary"],
["Clones", "Elementary"],
["Clones", "Elementary"],
["Minor Chicken", "Elementary"],
["Alice", "Middle School"],
["Mega Alice", "Middle School"],
["Jhon Doe", "Middle School"],
["Minor Bob", "Middle School"],
["alex", "Middle School"],
["Bob", "High School"],
["Jane Doe", "Undergrad"],
["Chicken", "Graduate"]
];
【问题讨论】:
-
我知道问题已结束,但我更新了我的答案,专门针对您要解决的问题。
标签: javascript arrays string sorting