If you debugged your function, you would have seen an error
Error: Cannot read property 'compareSortOrder' of undefined
So, passing the function reference 'this.compareSortOrder' to the sort function results in an instance reference loss within your compareSortOrder function.
You can use the bind() function for this:
nodes.sort(this.compareSortOrder.bind(this));
private compareSortOrder(a, b) {
if(a.children && a.children.length) {
a.children.sort(this.compareSortOrder.bind(this));
}
if(b.children && b.children.length) {
b.children.sort(this.compareSortOrder.bind(this));
}
// ...
}
Or provide an anonymous function to the sort function in order to preserve the this reference.
nodes.sort((n1, n2) => this.compareSortOrder(n1, n2));
private compareSortOrder(a, b) {
if(a.children && a.children.length) {
a.children.sort((n1, n2) => this.compareSortOrder(n1, n2));
}
if(b.children && b.children.length) {
b.children.sort((n1, n2) => this.compareSortOrder(n1, n2));
}
// ...
}
One more thing, you should also consider the case where the sortOrder might be equal. Further, if you want to have a consistent sorting, you'ld have to use an additional sorting attribute e.g. id or similar
if (a.sortOrder === b.sortOrder) {
return 0;
// or
// return a.id > b.id ? 1 : -1;
} else {
return a.sortOrder > b.sortOrder ? 1 : -1;
}