To start, let's modify the code to improve its readability.
It is worth noting that the ?:
part seems to have some questionable logic, as it uses ===
for comparison but then switches to non-strict comparisons like <
and >
. For the sake of clarity in this response, let's assume it is not meant for sorting arrays with mixed types or, if it is, it will disregard strict type checks (i.e., ===
should be replaced by ==
)
function orderArr (arr: any[], key: string) {
function sorter(a, b) {
return (
(a[key] > b[key])
? 1
: (a[key] === b[key])
? (
(a[key] > b[key])
? 1
: -1
)
: -1
);
}
return arr.sort(sorter);
}
export orderArr;
Let's now simplify the complex ?:
expression (complex not due to ?:
syntax but because it is overcomplicating things unnecessarily) by converting it to if-else statements (please note, this code is still incorrect)
function sorter(a, b) {
if (a[key] > b[key]) {
return 1; // return 1 if a > b
} else {
if (a[key] === b[key]) { // questionable logic
if (a[key] > b[key]) { // questionable logic
return 1;
} else {
return -1; // will always return -1 (wrong, a == b should return 0)
}
} else {
return -1; // return -1 if a < b
// or if type of a does not equal type of b (questionable)
}
}
}
We can further simplify and correct the bug (by removing the strict type comparison). This can be achieved using early return technique (guard clauses) and avoiding unnecessary indentation caused by excessive use of else statements
function sorter(a, b) {
if (a[key] > b[key]) return 1;
if (a[key] < b[key]) return -1;
return 0;
}
Alternatively, utilizing the ?:
syntax
function sorter(a, b) {
return a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0;
}
If you are dealing with numeric values, you can employ a simple trick to further streamline the code. As per the requirements of sort function – returning 0
for equal elements, negative for a < b
, and positive for a > b
- we can simplify numeric sorting as follows:
function sorter(a, b) {
return a[key] - b[key];
}
Now, let's consolidate all the simplified code into a single line. Firstly, for arrays of any data type.
export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0);
And for numerical arrays specifically
export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => a[key] - b[key]);