gpt4 book ai didi

javascript - 自定义排序二维数组

转载 作者:行者123 更新时间:2023-12-04 12:14:51 25 4
gpt4 key购买 nike

我有一个二维数组,它的条目代表一个员工,包括他们的经理的名字,有点像这样:

var array = [["Name", "Manager"],
["Leonard", "Penny"],
["Penny", "Professor Proton"],
["Sheldon", "Bernadette"],
["Raj", "Penny"],
["Professor Proton", "Professor Proton"],
["Howard", "Bernadette"],
["Bernadette", "Professor Proton"]]
如果员工和经理相同,则表示此人在层次结构中最高。我想要实现的是按字母顺序对经理下方的每个员工进行排序。换句话说,我想要的输出是这样的:
[["Name", "Manager"],
["Professor Proton", "Professor Proton"],
["Bernadette", "Professor Proton"],
["Howard", "Bernadette"],
["Sheldon", "Bernadette"],
["Penny", "Professor Proton"],
["Leonard", "Penny"],
["Raj", "Penny"]]
我的尝试是使用 array.sort(compare)具有以下“比较”功能:

var array = [
["Name", "Manager"],
["Leonard", "Penny"],
["Penny", "Professor Proton"],
["Sheldon", "Bernadette"],
["Raj", "Penny"],
["Professor Proton", "Professor Proton"],
["Howard", "Bernadette"],
["Bernadette", "Professor Proton"]
];

function compare(a, b) {

if (a[0] === a[1]) {
return -1;
}

if (b[0] === b[1]) {
return 1;
}

if (a[0] === b[1]) {
return -1;
}

if (b[0] === a[1]) {
return 1;
}


if (a[0].toLowerCase() < b[0].toLowerCase()) {
return -1;
}

if (a[0].toLowerCase() > b[0].toLowerCase()) {
return 1;
}

return 0;
}

console.log(array.sort(compare));

不幸的是,我得到的输出只是一个按员工姓名字母顺序排序的数组。另外,“标题”也包含在排序中,我不想发生这种情况。
我做错了什么,除了使用 Array.prototype.sort() 之外的任何提示或替代建议?
请好心人帮帮我!

最佳答案

您需要一棵树并以深度优先遍历的方式获取项目。这种(新方法)无需更改有效负载即可工作。

const
sort = array => {
const
t = {},
getManager = data => data[0] === data[1] ? '' : data[1],
getData = manager => (t[manager] || [])
.sort(([a], [b]) => a.localeCompare(b))
.flatMap(data => [data, ...getData(data[0])]);

array.forEach(data => (t[getManager(data)] ??= []).push(data));

return getData('');
},
data = [["Name", "Manager"], ["Leonard", "Penny"], ["Penny", "Professor Proton"], ["Sheldon", "Bernadette"], ["Raj", "Penny"], ["Professor Proton", "Professor Proton"], ["Howard", "Bernadette"], ["Bernadette", "Professor Proton"]],
result = [data[0], ...sort(data.slice(1))];

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 自定义排序二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69368065/

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