JavaScript Arrays: Properties, Methods, and Manipulation (Part 4 of 7)

Corey Schafer · Beginner ·🌐 Frontend Engineering ·11y ago

Key Takeaways

This video series covers JavaScript Arrays, focusing on properties, methods, and manipulation, with part 4 exploring the sort() method and custom sorting using compare functions.

Full Transcript

now by default the sort method doesn't work exactly like we'd expect it to if i uncomment out this code here you can see i have an array of numbers here that are all jumbled up and if i just run the sort method on this ray13 dot sort and then i output this to the screen and you can see that this sorted array isn't exactly what we were expecting and instead of 1 2 3 4 10 20 30 40 we're getting 110 220 330. the reason it does this is because by default the sort method uses the unicode values to sort by and this is how these values are sorted in unicode if we want to sort these values in any other way then we need to manually tell javascript how they should be sorted and the way that we do that is with a compare function so what a compare function is let me go ahead and write one of these out and that would be the best way to explain it so function and i'm just going to call this sort nums and a compare function takes in two values i'm just gonna have this take in a and b two parameters um so you can see i have commented down here if we return a value that is greater than zero then we're telling javascript to that the way this array should be sorted is that the b should come before the a uh if it returns a zero we're saying that these values are equal and that it doesn't matter about the sort order so it'll be unchanged if we return a value that is less than 0 then we're saying that a should come before b so say that we are passing in numbers to this sort to this compare function um so let's just uh pick two random numbers here let's say a is 10 and let's say b is 20. and so we want this function if it runs into these two parameters to return a number that is less than 0 because we want a to come before b because 10 is less than 20. so how could we do that well if we did 10 minus 20 that equals negative 10 that is a number that is less than zero so we're telling javascript that a should come before b so in this case if we wanted to sort in ascending order that would be correct because a is less than b if a was 30 then this would be 30 minus 20 and then that would return 10 and that's also what we want because now a is greater than b this returns a number that is greater than zero so we're saying that b needs to come before a so we're saying 20 needs to come before 30. and if a was 30 and b was 30 that would be 30 minus 30 equals 0 and that returns 0 and it's just saying that these values are equal and that the sword order doesn't matter so to sort this in ascending order we could just do a return a minus b and then if i pass this compare function into the sort method then now you can see down here that our array is sorted the way that we uh think it should be one two three four ten twenty thirty forty and now the great thing about these compare functions is that you can customize them any way you want if you want this to be sorted by descending order then we can just do b minus a and now it's sorted by descending order 40 30 20 10 4 3 2 1. so that's a brief look at sorting numbers now let's take a look at sorting some strings here so let me take away that compare function so we are just using the default sort method to sort these strings so i have jack jill cory pete and ann and you can see that the using sort by default kind of looks like it works here but then if we take a look at the end it didn't actually do exactly what we wanted because and is lower case and like i said before this sorts by the unicode values and in unicode these uppercase characters are larger than the lowercase characters so if we wanted this to be case insensitive then we have to write our own compare function for that um so let's go ahead and write a quick compare function and see how we would do this so i'm gonna i'm going to call this one sort alpha and i'm also going to pass in a b usually for compare functions those will be the parameters something like that a b so what we can do here is now we want to uh sort these by the lowercase version of these strings we want it to be case insensitive so what we can do is we can make a variable inside our function and just call it a lower equals a dot to lower case and then we can either make another variable called b lower equals b dot to lower case and then we can just compare these strings so we can say if a lower is less than b lower then we can return negative one because remember if we want uh a to be before b then it needs to be a number that is less than zero so we're going to return negative one for that um so let me go ahead and copy this and paste it in if a lower is greater than b lower then we want to turn positive one and if it's neither of those which in this case it would mean that it's equal then we would just return 0 okay and now let's go ahead and pass this compare function into our sort method and whenever we save that and look at the sorted values now now then you can see that this sorts the way that we want it to be sorted it's case insensitive so we have ann cory jack jill and pete okay so that was a quick look at sorting some strings now let's take a look at sorting some objects so i have a sample object here so let me uncomment this and let me go ahead and uncomment out the code that will display this to the html um okay so what this object is is it's an object of names and each object has a first property and a last property for first name and last name um so now let's uh say that we want to sort this first by first name and then by last name so if we look at the comments here you can see my original array of the way that it's displaying now is joe smith and smith tom doe and ando and then in this comment here we have the desired sorting would be ando and smith joe smith and tomdo so we're sorting on the first name first and if the first names are the same then we want to sort on the last name so ando would come before ann smith so we know we're going to need a custom compare function to do this so let's write one called sort names and we're just going to use the same a and b parameters and then let's go ahead and try to reuse some of the code that we used before so let's take this sort alpha function that we wrote earlier and let's paste that into our sort names so then let's take this function and let's go ahead and try to sort this and see what happens so whenever i save that it's not displaying anything so there's most likely an error in here now what's going on is that we need to realize that now we're trying to sort objects now we're trying to sort objects instead of just the strings themselves so whenever we say a dot lower case here it doesn't know uh what it is that we're trying to access so these are the same objects that it is that we're trying to sort so they have the same properties so a lower instead of a dot lower case really needs to be that a object and then the first property and then to lower case and then b dot first dot two or lower case and if i save that then you can see here um that it is now sorted on the first name so now we have ann smith ando joe smith and tomdo but you can see here it's sorted on the first name and the last names are still out of order so we have ann smith and we have ando so how can we do this to where it sorts on the first name first and if those are equal then it'll sort on the last name so all we have to do here is we're going to be sorting on multiple parameters so let's put in an if statement here and just say if now these are the first names here i should probably rename these but i'm just going to leave them the way that they are so if these first names are equal then now we want to sort on the last name so now we can take the same logic that we use for the first names copy that and we can paste it up here into this if statement and now we want to sort on the last name so let's go ahead and to lower case those also so let's paste those in and instead of a lower i'm going to call this a last and instead of b lower i'm going to call this b last and now instead of the first names we want to grab the last property and let's copy that so now remember a lower and b lower are the first names when those are equal then we want to come in here and sort both of these based on the last name so if the last name if the a last name is less than the b last name return negative one and if it is greater than the b last name return one and if it's the same just return zero so let's go ahead and save that and then you can look down here and see that our array of names is sorted exactly how we want it to be sorted so it's sorted by first name and then it's sorted by last name okay so that is a quick look at sorts and a few different examples of that now let's go ahead and take a look at the filter method

Original Description

JavaScript Arrays: Properties, Methods, and Manipulation (Part 4 of 7) In this series, we will take an in-depth look at JavaScript Arrays and everything we can do with them. In part 4, we will go over: sort() Part 1: https://youtu.be/8JgU2WmrZXI Part 2: https://youtu.be/nAWVYFEzoY8 Part 3: https://youtu.be/cdPS-lmlwco ... Part 5: https://youtu.be/w4KF_lapbRI Part 6: https://youtu.be/1gupsllu5wQ Part 7: https://youtu.be/qxzp4X6sfGo ✅ Support My Channel Through Patreon: https://www.patreon.com/coreyms ✅ Become a Channel Member: https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join ✅ One-Time Contribution Through PayPal: https://goo.gl/649HFY ✅ Cryptocurrency Donations: Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3 Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33 Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot ✅ Corey's Public Amazon Wishlist http://a.co/inIyro1 ✅ Equipment I Use and Books I Recommend: https://www.amazon.com/shop/coreyschafer ▶️ You Can Find Me On: My Website - http://coreyms.com/ My Second Channel - https://www.youtube.com/c/coreymschafer Facebook - https://www.facebook.com/CoreyMSchafer Twitter - https://twitter.com/CoreyMSchafer Instagram - https://www.instagram.com/coreymschafer/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Corey Schafer · Corey Schafer · 19 of 60

1 Web fonts using CSS Font Face
Web fonts using CSS Font Face
Corey Schafer
2 Using Font Awesome in Desktop Applications (OS X)
Using Font Awesome in Desktop Applications (OS X)
Corey Schafer
3 Sublime Text 2: Setup, Package Control, and Settings
Sublime Text 2: Setup, Package Control, and Settings
Corey Schafer
4 ArcGIS API for JavaScript Part 1: Our First Web Map
ArcGIS API for JavaScript Part 1: Our First Web Map
Corey Schafer
5 Mac Tip: Windows' Snapping Feature on Mac with HyperDock
Mac Tip: Windows' Snapping Feature on Mac with HyperDock
Corey Schafer
6 Linux/Mac Terminal Tutorial: Creating Aliases for Commands
Linux/Mac Terminal Tutorial: Creating Aliases for Commands
Corey Schafer
7 ArcGIS API for JavaScript Part 2: Starting Templates
ArcGIS API for JavaScript Part 2: Starting Templates
Corey Schafer
8 Paver Patio Time Lapse
Paver Patio Time Lapse
Corey Schafer
9 Mac Tip: Ways to perform Screen Capturing and Screenshots
Mac Tip: Ways to perform Screen Capturing and Screenshots
Corey Schafer
10 WordPress Plugins: Imsanity
WordPress Plugins: Imsanity
Corey Schafer
11 WordPress Tips: Test your theme with Theme Unit Test and Monster Widget
WordPress Tips: Test your theme with Theme Unit Test and Monster Widget
Corey Schafer
12 Sublime Text 3: Setup, Package Control, and Settings
Sublime Text 3: Setup, Package Control, and Settings
Corey Schafer
13 Understanding Binary, Hexadecimal, Decimal (Base-10), and more
Understanding Binary, Hexadecimal, Decimal (Base-10), and more
Corey Schafer
14 Mac Tip: Adding Folder Stacks to the Dock
Mac Tip: Adding Folder Stacks to the Dock
Corey Schafer
15 CSS Tips and Tricks: Add External URLs to Print Stylesheets
CSS Tips and Tricks: Add External URLs to Print Stylesheets
Corey Schafer
16 JavaScript Arrays: Properties, Methods, and Manipulation (Part 7 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 7 of 7)
Corey Schafer
17 JavaScript Arrays: Properties, Methods, and Manipulation (Part 1 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 1 of 7)
Corey Schafer
18 JavaScript Arrays: Properties, Methods, and Manipulation (Part 5 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 5 of 7)
Corey Schafer
JavaScript Arrays: Properties, Methods, and Manipulation (Part 4 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 4 of 7)
Corey Schafer
20 JavaScript Arrays: Properties, Methods, and Manipulation (Part 3 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 3 of 7)
Corey Schafer
21 JavaScript Arrays: Properties, Methods, and Manipulation (Part 2 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 2 of 7)
Corey Schafer
22 JavaScript Arrays: Properties, Methods, and Manipulation (Part 6 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 6 of 7)
Corey Schafer
23 Python Tutorial: if __name__ == '__main__'
Python Tutorial: if __name__ == '__main__'
Corey Schafer
24 Sublime Text Quick Tip: "Go To Definition" Click Shortcut
Sublime Text Quick Tip: "Go To Definition" Click Shortcut
Corey Schafer
25 How to quickly create favicons for the desktop, Apple/Android devices, tablets, and more
How to quickly create favicons for the desktop, Apple/Android devices, tablets, and more
Corey Schafer
26 Easily Resize Multiple Images Using Picasa
Easily Resize Multiple Images Using Picasa
Corey Schafer
27 Easily Resize Multiple Images Using the Mac Terminal
Easily Resize Multiple Images Using the Mac Terminal
Corey Schafer
28 Python Tutorial: virtualenv and why you should use virtual environments
Python Tutorial: virtualenv and why you should use virtual environments
Corey Schafer
29 Python Tutorial: pip - An in-depth look at the package management system
Python Tutorial: pip - An in-depth look at the package management system
Corey Schafer
30 Git Tutorial: Using the Stash Command
Git Tutorial: Using the Stash Command
Corey Schafer
31 How Software Engineers, Developers, and Designers can volunteer their skills
How Software Engineers, Developers, and Designers can volunteer their skills
Corey Schafer
32 Git Tutorial: Diff and Merge Tools
Git Tutorial: Diff and Merge Tools
Corey Schafer
33 Git Tutorial: Change DiffMerge Font-Size on Mac OSX
Git Tutorial: Change DiffMerge Font-Size on Mac OSX
Corey Schafer
34 Sublime Text Quick Tip: Launch Sublime Text from the Terminal
Sublime Text Quick Tip: Launch Sublime Text from the Terminal
Corey Schafer
35 Python Tutorial: str() vs repr()
Python Tutorial: str() vs repr()
Corey Schafer
36 Programming Terms: DRY (Don't Repeat Yourself)
Programming Terms: DRY (Don't Repeat Yourself)
Corey Schafer
37 Programming Terms: String Interpolation
Programming Terms: String Interpolation
Corey Schafer
38 Programming Terms: Idempotence
Programming Terms: Idempotence
Corey Schafer
39 Python Tutorial: Namedtuple - When and why should you use namedtuples?
Python Tutorial: Namedtuple - When and why should you use namedtuples?
Corey Schafer
40 Programming Terms: Mutable vs Immutable
Programming Terms: Mutable vs Immutable
Corey Schafer
41 Python Tutorial: Else Clauses on Loops
Python Tutorial: Else Clauses on Loops
Corey Schafer
42 Overview of Online Learning Resources
Overview of Online Learning Resources
Corey Schafer
43 Mac OS X Terminal Tutorial: Time-Saving Keyboard Shortcuts
Mac OS X Terminal Tutorial: Time-Saving Keyboard Shortcuts
Corey Schafer
44 Git Tutorial for Beginners: Command-Line Fundamentals
Git Tutorial for Beginners: Command-Line Fundamentals
Corey Schafer
45 Quickest and Easiest Way to Run a Local Web-Server
Quickest and Easiest Way to Run a Local Web-Server
Corey Schafer
46 Python Tutorial: Generators - How to use them and the benefits you receive
Python Tutorial: Generators - How to use them and the benefits you receive
Corey Schafer
47 Python Tutorial: Comprehensions - How they work and why you should be using them
Python Tutorial: Comprehensions - How they work and why you should be using them
Corey Schafer
48 Chrome Quick Tip: Quickly Bookmark Open Tabs for Later Viewing
Chrome Quick Tip: Quickly Bookmark Open Tabs for Later Viewing
Corey Schafer
49 Programming Terms: Combinations and Permutations
Programming Terms: Combinations and Permutations
Corey Schafer
50 Git Tutorial: Difference between "add -A", "add -u", "add .", and "add *"
Git Tutorial: Difference between "add -A", "add -u", "add .", and "add *"
Corey Schafer
51 Preparing for a Python Interview: 10 Things You Should Know
Preparing for a Python Interview: 10 Things You Should Know
Corey Schafer
52 SQL Tutorial for Beginners 1: Installing PostgreSQL and Creating Your First Database
SQL Tutorial for Beginners 1: Installing PostgreSQL and Creating Your First Database
Corey Schafer
53 SQL Tutorial for Beginners 2: Creating Your First Table
SQL Tutorial for Beginners 2: Creating Your First Table
Corey Schafer
54 SQL Tutorial for Beginners 3: INSERT - Adding Records to Your Database
SQL Tutorial for Beginners 3: INSERT - Adding Records to Your Database
Corey Schafer
55 Linux/Mac Terminal Tutorial: Navigating your Filesystem
Linux/Mac Terminal Tutorial: Navigating your Filesystem
Corey Schafer
56 Python: Ex Machina Easter Egg - Hidden Message within the Code
Python: Ex Machina Easter Egg - Hidden Message within the Code
Corey Schafer
57 Mac Tip: New Split Screen Feature in El Capitan
Mac Tip: New Split Screen Feature in El Capitan
Corey Schafer
58 Setting up a Python Development Environment in Eclipse
Setting up a Python Development Environment in Eclipse
Corey Schafer
59 Git Tutorial: Fixing Common Mistakes and Undoing Bad Commits
Git Tutorial: Fixing Common Mistakes and Undoing Bad Commits
Corey Schafer
60 SQL Tutorial for Beginners 4: SELECT - Retrieving Records from Your Database
SQL Tutorial for Beginners 4: SELECT - Retrieving Records from Your Database
Corey Schafer

This video teaches how to use the sort() method in JavaScript Arrays, including custom sorting using compare functions, to sort numbers and strings in ascending or descending order.

Key Takeaways
  1. Run the sort method on an array of numbers with a compare function
  2. Pass in two values to the compare function and return a number to determine the sort order
  3. Use the compare function to sort numbers in ascending or descending order
  4. Create a custom compare function to sort objects by multiple properties
  5. Pass the custom compare function to the sort method to sort the array
💡 The sort() method uses Unicode values by default, but a custom compare function can be used to sort values in a custom way.

Related AI Lessons

Had my Frontend Developer interview with Capgemini (Application Developer) today, and I wanted to…
Prepare for a frontend developer interview with Capgemini by reviewing JavaScript fundamentals and practicing common interview questions
Medium · JavaScript
10 Frontend Developer Tools to Boost Productivity in 2026
Boost frontend productivity with 10 essential tools for modern web app development
Medium · Programming
10 Frontend Developer Tools to Boost Productivity in 2026
Boost frontend productivity with top 10 developer tools in 2026
Medium · JavaScript
The US Frontend Engineer Market in 2026: A Data-Driven Reality Check (and the Bias That Stops Us Seeing It)
US frontend engineer hiring demand peaked in 2022 and remains flat-depressed in 2026, contrary to common assumptions
Dev.to AI
Up next
The masks we wear | Zora Krstić | TEDxLuxembourgCity
TEDx Talks
Watch →