I have a 2D array whose entries represent an employee including the name of their manager, sort of like this:
var array = [["Name", "Manager"],
["Leonard", "Penny"],
["Penny", "Professor Proton"],
["Sheldon", "Bernadette"],
["Raj", "Penny"],
["Professor Proton", "Professor Proton"],
["Howard", "Bernadette"],
["Bernadette", "Professor Proton"]]
If the employee and the manager are the same, it means that the person is highest up in the hierarchy. What I want to achieve is to sort each employee below their manager, alphabetically. In other words, the output I want is this:
[["Name", "Manager"],
["Professor Proton", "Professor Proton"],
["Bernadette", "Professor Proton"],
["Howard", "Bernadette"],
["Sheldon", "Bernadette"],
["Penny", "Professor Proton"],
["Leonard", "Penny"],
["Raj", "Penny"]]
My attempt was to use array.sort(compare) with the following "compare" function:
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));
Unfortunately, what I get as output is just an array sorted alphabetically by the name of the employee. Plus, the "header" is included in the sort as well, which I want not to happen.
What am I doing wrong, any tips or alternative suggestions other than using Array.prototype.sort()?
Please, kind soul, help me!