I attempted to use condition to sort array by different fields:
return source.sort((a, b) => {
if (a.orderBy && b.orderBy) {
return sortOrder === 'asc'
? a.orderBy - b.orderBy
: b.orderBy - a.orderBy;
}
return sortOrder === 'asc' ? a.name - b.name : b.name - a.name;
});
I have got the error:
The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
What is problem?
It works for me, but probably it could be better:
return source.sort((a, b) => {
if (a.orderBy && b.orderBy) {
return sortOrder === 'asc'
? a.orderBy - b.orderBy
: b.orderBy - a.orderBy;
}
if (sortOrder === 'asc') {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
} else {
if (a.name > b.name) {
return -1;
}
if (a.name < b.name) {
return 1;
}
return 0;
}
});