2023-05-08

Javascript :: Sort array of strings (or numbers) ascending and descending

Sorting an array of strings is a common scenario and it's almost mostly enough to just use sort():

var myArray = ["3", "2", "4", "1"];
myArray.sort();
console.log(JSON.stringify(myArray));
//outputs: ["1","2","3","4"]

However if doing descending order, need to use a comparison function:

// descending order
var myArray = ["3", "2", "4", "1"];
myArray.sort(function (a, b) {
    if (a > b) {
        return -1;
    }
    if (b > a) {
        return 1;
    }
    return 0;
});
console.log(JSON.stringify(myArray));
//outputs: ["4","3","2","1"]

Look into the Sort keyword for other variants.

No comments:

Post a Comment

Please provide any feedback or post questions here...

Javascript :: comparison operators, using == vs === and != vs !==

Comparison operators are distinguished following simple logic, whether data type is being included or not. Essentially if it is === or !==, ...