I want to sort an array in ascending and descending order, also I want a specific "-" value at the bottom when the array is sorted in ascending order and want the same value to be at the top in array when it is sorted in descending order.
Example:- array: ["-", "a", "z", "-", "b"], ascending order: ["a", "b", "z", "-", "-"], descending order: ["-", "-", z, "b", "a"]
I have tried the below code but the "-" always stay at the top. Please help to find what mistake I am making here. Thanks in advance!
function alphabetically(ascending) {
return function (a, b) {
// equal items sort equally
if (a === b) {
return 0;
}
// nulls sort after anything else
if (a === "-") {
return -1;
}
if (b === "-") {
return 1;
}
// otherwise, if we're ascending, lowest sorts first
if (ascending) {
return a < b ? -1 : 1;
}
// if descending, highest sorts first
return a < b ? 1 : -1;
};
}
var arr = ["-", "a", "z", "-", "b"];
console.log(arr.sort(alphabetically(true)));
console.log(arr.sort(alphabetically(false)));
>Solution :
Because you don’t consider the ascending variable when deciding what to do with "-" values:
if (a === "-") {
return -1;
}
if (b === "-") {
return 1;
}
If you want that result to change based on ascending, add it to that logic:
function alphabetically(ascending) {
return function (a, b) {
// equal items sort equally
if (a === b) {
return 0;
}
// nulls sort after anything else
if (a === "-") {
return ascending ? 1 : -1;
}
if (b === "-") {
return ascending ? -1 : 1;
}
// otherwise, if we're ascending, lowest sorts first
if (ascending) {
return a < b ? -1 : 1;
}
// if descending, highest sorts first
return a < b ? 1 : -1;
};
}
var arr = ["-", "a", "z", "-", "b"];
console.log(arr.sort(alphabetically(true)));
console.log(arr.sort(alphabetically(false)));