1// function that returns a string in alphabetical order
2function reorderStr(str) {
3 return [...str].sort().join('');
4}
5console.log(reorderStr("hacker")); //"acehkr"
6console.log(reorderStr("javascript"));//"aacijprstv"
1arr = ['width', 'score', done', 'neither' ]
2arr.sort() // results to ["done", "neither", "score", "width"]
3
4arr.sort((a,b) => a.localeCompare(b))
5// if a-b (based on their unicode values) produces a negative value,
6// a comes before b, the reverse if positive, and as is if zero
7
8//When you sort an array with .sort(), it assumes that you are sorting strings
9//. When sorting numbers, the default behavior will not sort them properly.
10arr = [21, 7, 5.6, 102, 79]
11arr.sort((a, b) => a - b) // results to [5.6, 7, 21, 79, 102]
12// b - a will give you the reverse order of the sorted items
13
14//this explnation in not mine
1//sorts arrays of numbers
2function myFunction() {
3 points.sort(function(a, b){return a-b});
4 document.getElementById("demo").innerHTML = points;
5}
1const months = ['March', 'Jan', 'Feb', 'Dec'];
2months.sort();
3console.log(months);
4// expected output: Array ["Dec", "Feb", "Jan", "March"]
1var names = ["Peter", "Emma", "Jack", "Mia"];
2var sorted = names.sort(); // ["Emma", "Jack", "Mia", "Peter"]