showing results for - "8 3 1 common array methods 2f 2f sort examples 28 sort 29"
Adrien
09 Apr 2016
1//The general syntax for this method is:
2arrayName.sort()
3
4/*This method arranges the elements of an array into increasing order. 
5For strings, this means alphabetical order. HOWEVER, the results are 
6not always what we expect.*/
7
8let letters = ['f', 'c', 'B', 'X', 'a'];
9
10letters.sort();
11console.log(letters);
12
13//[ 'B', 'X', 'a', 'c', 'f' ]
14
15/*From the alphabet song, we know that 'a' comes before 'B' 
16(and certainly before 'X'), but JavaScript treats capital and lowercase
17letters differently. The default sort order places capital letters 
18before lowercase.*/
19
20//Example: 
21let mixed = ['a', 'A', 20, 40];
22
23mixed.sort();
24console.log(mixed);
25
26//[ 20, 40, 'A', 'a' ]
27
28/*When numbers and strings are sorted, the default order places 
29numbers before all letters.*/
30
31//Example:
32//Numerical sorting.
33
34let numbers = [2, 8, 10, 400, 30];
35
36numbers.sort();
37console.log(numbers);
38Output
39
40//[ 10, 2, 30, 400, 8 ]
41
42/*Here JavaScript gets truly bizarre. How is 8 larger than 400?
43
44When JavaScript sorts, it converts all entries into strings by 
45default. Just like 'Apple' comes before 'Pear' because 'A' comes 
46before 'P', the string '400' begins with a '4', which comes before 
47any string starting with an '8'. Looking only at the first digit in 
48each number, we see the expected progression (1, 2, 3, 4, 8).
49
50Later in this course, we will explore ways to fix this issue and 
51correctly sort numerical arrays.*/