Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort a specific value "-" at bottom when sorting is in ascending order and to the top when it is in descending order?

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading