8.3.1. Common Array Methods // sort Examples (.sort)
//The general syntax for this method is:
arrayName.sort()
/*This method arranges the elements of an array into increasing order.
For strings, this means alphabetical order. HOWEVER, the results are
not always what we expect.*/
let letters = ['f', 'c', 'B', 'X', 'a'];
letters.sort();
console.log(letters);
//[ 'B', 'X', 'a', 'c', 'f' ]
/*From the alphabet song, we know that 'a' comes before 'B'
(and certainly before 'X'), but JavaScript treats capital and lowercase
letters differently. The default sort order places capital letters
before lowercase.*/
//Example:
let mixed = ['a', 'A', 20, 40];
mixed.sort();
console.log(mixed);
//[ 20, 40, 'A', 'a' ]
/*When numbers and strings are sorted, the default order places
numbers before all letters.*/
//Example:
//Numerical sorting.
let numbers = [2, 8, 10, 400, 30];
numbers.sort();
console.log(numbers);
Output
//[ 10, 2, 30, 400, 8 ]
/*Here JavaScript gets truly bizarre. How is 8 larger than 400?
When JavaScript sorts, it converts all entries into strings by
default. Just like 'Apple' comes before 'Pear' because 'A' comes
before 'P', the string '400' begins with a '4', which comes before
any string starting with an '8'. Looking only at the first digit in
each number, we see the expected progression (1, 2, 3, 4, 8).
Later in this course, we will explore ways to fix this issue and
correctly sort numerical arrays.*/
Are there any code examples left?
New code examples in category Javascript
-
Javascript 2023-04-21 22:52:36
-
Javascript 2022-03-27 22:25:20 javascript download string as file
-
Javascript 2022-03-27 21:40:22 sort numbers in array javascript
-
Javascript 2022-03-27 21:20:04 compare two arrays and return the difference javascript
-
Javascript 2022-03-27 21:15:02 javascript regex french phone number
-
Javascript 2022-03-27 21:05:03 cypress custom error message
-
Javascript 2022-03-27 21:00:05 create element javascript with id
-
Javascript 2022-03-27 20:40:57 feather icons react
-
Javascript 2022-03-27 20:20:01 how to make graphql request in axios
-
Javascript 2022-03-27 20:15:07 bootstrap validator password and confirm password