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?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source