[英]Sorting array inside array alphabetically
我有一个这样的数组:
const test = [
{
label: "C",
options: [
{ label: "C"},
{ label: "B"}
]
},
{
label: "A",
options: [
{ label: "Z"},
{ label: "Y"}
]
},
{
label: "B",
options: [
{ label: "J"},
{ label: "H"}
]
},
{
label: "D",
options: [
{ label: "T"},
{ label: "B"}
]
}
]
我需要以两种方式按字母顺序对这个数组进行排序:
1)通过第一个标签(在 options 数组之外)
2)以及标签选项
到目前为止,我只设法按第一个标签排序,使用以下示例:
function compareStrings(a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
test.sort(function (a, b) {
return compareStrings(a.label, b.label)
})
我怎样才能订购里面的选项?
预期的输出数组将是:
const test_SORTED = [
{
label: "A",
options: [
{ label: "B"},
{ label: "C"}
]
},
{
label: "B",
options: [
{ label: "Y"},
{ label: "Z"}
]
},
{
label: "C",
options: [
{ label: "H"},
{ label: "J"}
]
},
{
label: "D",
options: [
{ label: "B"},
{ label: "T"}
]
}
]
在对测试数组进行排序时,我也对选项数组进行了排序。
const test = [ { label: "C", options: [ { label: "C"}, { label: "B"} ] }, { label: "A", options: [ { label: "Z"}, { label: "Y"} ] }, { label: "B", options: [ { label: "J"}, { label: "H"} ] }, { label: "D", options: [ { label: "T"}, { label: "B"} ] } ]; function compareStrings(a, b) { a = a.toLowerCase(); b = b.toLowerCase(); return (a < b) ? -1 : (a > b) ? 1 : 0; } console.log( test.sort(function (a, b) { a.options = a.options.sort(function (c, d) { return compareStrings(c.label, d.label) }) b.options = b.options.sort(function (e, f) { return compareStrings(e.label, f.label) }) return compareStrings(a.label, b.label) }) )
您应该使用 forEach 循环分别对每个元素的选项进行排序,以避免在使用 sort 方法时对它们进行多次排序。
const comparator = (a, b) => (a.label < b.label ? -1 : a.label > b.label ? 1 : 0);
test.sort(comparator);
test.forEach(el => el.options.sort(comparator));
此外, sort 直接更改数组,因此无需为选项分配值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.