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;
});
if (a > b) {
return -1;
}
if (b > a) {
return 1;
}
return 0;
});
console.log(JSON.stringify(myArray));
//outputs: ["4","3","2","1"]
//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...