Instead of starting with a one line if-statement. I prefer to use more lines of code to easier understand the logic which has to be performed
// return 1 if x has more value/larger than y
// return -1 if x has less value/smaller than y
data.sort(function (x, y) {
// type has priority over cod. So cod can be ignored if type is different for x and y
if (x.type == true && y.type == false) {
return 1;
}
if (x.type == false && y.type == true) {
return -1;
}
// If type is the same for y and x, compare the cod value instead!
if (x.type == y.type) {
if (x.cod > y.cod) {
return 1;
}
if (x.cod < y.cod) {
return -1;
}
}
// Return 0 if they have the exact same
return 0;
});
Reducing the code a bit by subtracting the cod numbers instead. Negative means y.cod is larger, positive mean x.cod is larger. zero means they are equal.
data.sort(function (x, y) {
if (x.type == true && y.type == false) {
return 1;
}
if (x.type == false && y.type == true) {
return -1;
}
// If type is the same for y and x, compare the cod value instead!
if (x.type == y.type) {
// Can be condensed to a single subtraction
return x.cod - y.cod;
}
});
Can be improved further with fewer comparisons
data.sort(function (x, y) {
// these are equivalent to the first two if-statements in the code blocks above.
if (x.type && !y.type) return 1;
if (!x.type && y.type) return -1;
// if none of above has been triggered, the types are equal and cod should be compared.
return x.cod - y.cod;
});
And as @Eliseo suggested, it can be condensed with ternary operators which will reduce execution time.
data.sort(function (x,y) {
return !x.type && y.type ? 1 : (x.type && !y.type ? -1 : x.cod-y.cod);
});
For understanding it's easier to start with the most straight forward one where the logic can be followed easily. Then from there see what can be done to simplify it.
return x.type ? -1 : x.cod - y.cod;