|
1 | 1 | 
|
2 | 2 |
|
3 | 3 | # Sorting
|
4 |
| -This MD file serves as example/template. It will be filled up soon. |
| 4 | +Sometimes we need to sort the stored values of our array. In order to do that we usually use the .sort() function: |
| 5 | + |
5 | 6 |
|
6 |
| -(for Bucky to fill up) |
| 7 | + console.log(items.sort()); |
7 | 8 |
|
8 | 9 | # Course Documentation
|
9 | 10 |
|
10 |
| -(this for me to fill up with every element that you use in lessons. syntax explaination and links for more) |
| 11 | +## .sort() |
| 12 | + |
| 13 | +According to [w3schools](http://www.w3schools.com/jsref/jsref_sort.asp): |
| 14 | + |
| 15 | + "The sort() method sorts the items of an array. |
| 16 | +The sort order can be either alphabetic or numeric, and either ascending (up) or descending (down). |
| 17 | +By default, the sort() method sorts the values as strings in alphabetical and ascending order. |
| 18 | +This works well for strings ("Apple" comes before "Banana"). **However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".** |
| 19 | +Because of this, the sort() method will produce an incorrect result when sorting numbers. |
| 20 | +You can fix this by providing a "compare function" (See "Parameter Values" below)." |
| 21 | + |
| 22 | + let items = [1, 10, 17, 18, 2, 7, 3, 19, 14, 5]; |
| 23 | + console.log(items.reverse()); |
| 24 | + |
| 25 | + // not what we wanted, because it sorts the numbers as if they are all strings |
| 26 | + console.log(items.sort()); |
| 27 | + |
| 28 | +###compareFunction |
11 | 29 |
|
12 |
| -## Element to explain |
| 30 | +Optional. A function that defines an alternative sort order. The function should return a negative, zero, or positive value, depending on the arguments, like: |
13 | 31 |
|
14 |
| -(for example console.log) |
| 32 | + function(a, b){return a-b} |
| 33 | + |
| 34 | +When the sort() method compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value. |
| 35 | + |
| 36 | + items.sort(function (a, b) { |
| 37 | + return a - b; |
| 38 | + }); |
| 39 | + console.log(items); |
| 40 | + |
| 41 | +[Read more about sort() function on W3schools](http://www.w3schools.com/jsref/jsref_sort.asp). |
15 | 42 |
|
16 | 43 | ##Javascript functions
|
17 | 44 |
|
@@ -124,4 +151,6 @@ stack in order to remove things from it.
|
124 | 151 | - [Twitter](https://twitter.com/bucky_roberts)
|
125 | 152 | - [Google+](https://plus.google.com/+BuckyRoberts)
|
126 | 153 | - [reddit](https://www.reddit.com/r/thenewboston/)
|
| 154 | + |
| 155 | + |
127 | 156 | > Written with [StackEdit](https://stackedit.io/).
|
0 commit comments