Sorting Arrays in JavaScript

Melissa Guachun - Jun 1 '22 - - Dev Community

Sorting is one of the many essential method that you will use when learning JavaScript. Let's go over how we use the sorting method with different data types.


Strings
The sort method by default organizes its elements alphabetically.

const names = ['Sophie', 'Fletcher', 'Emmy', 'Izzy', 'Cooper']

const sortNames = names.sort()

console.log(sortNames)

//['Cooper', 'Emmy', 'Fletcher', 'Izzy', 'Sophie']
Enter fullscreen mode Exit fullscreen mode

We can also sort this array in reverse order just as easily!

const reversedNames = sortNames.reverse()

console.log(reversedNames)

// ['Sophie', 'Izzy', 'Fletcher', 'Emmy', 'Cooper']
Enter fullscreen mode Exit fullscreen mode

Numbers
When sorting numbers, we use a callback function to handle the comparison of values.

const nums = [10, 855, 31, 2, 930, 430, 529, 59]

const sortedNums = numbers.sort((a, b) => a - b)

console.log(sortedNums)

//[2, 10, 31, 59, 430, 529, 855, 930]

Enter fullscreen mode Exit fullscreen mode

Strings with Numbers
This example pertains when a string has an injected number that is less than 10. (There will be a more extensive version of this example in a later example!). In this example, we will use slice() and turn the string with an injected number into a number. This way, we are able to sort all of the array elements where every element is the same data type.

const library = ['Book 1', 'Book 6', 'Book 2', 'Book 4', 'Book 3', 'Book 5']

const sortedLibrary = library.sort((a, b) => {
return +a.slice(-1) - +b.slice(-1)
})

console.log(sortedLibrary)
// ['Book 1', 'Book 2', 'Book 3', 'Book 4', 'Book 5', 'Book 6']
Enter fullscreen mode Exit fullscreen mode

Strings with Long Numbers
For numbers larger than 9, here is a way to use regular expressions to find and sort the elements based on their values.

In this example we will be using regular expressions.

Regular expressions aka Regex is sequence of characters that forms a search pattern. The search pattern can be used for text search and text replace operations.

(Regex can be really intimidating when first faced with it. I personally still find it confusing. Appearances aside, it's a highly usable and powerful type of code that can be useful in many situations.)

Let's first break down what our regular expression will look like:


const coolRegex = /\d+/

Enter fullscreen mode Exit fullscreen mode
  • The first and last / in coolRegex stands for the expression's boundaries.

  • \d stands for digit

  • + means, '1 or more times'

So, in it's entirety, our regular expression is enabling us to find elements that are bigger than 9 and sort the elements of the array.

Let's move onto our full example:


const coolRegex = /\d+/;

const longLibrary = [
    'Book 339',
    'Book 868',
    'Book 23',
    'Book 90',
    'Book 5', 
    'Book 41',
    'Book 375'

]

const sortedLibrary = longLibrary.sort((a, b) => {
   return a.match(coolRegex) - b.match(coolRegex)
})

console.log(sortedLibrary)

//['Book 5', 'Book 23', 'Book 41', 'Book 90', 'Book 339', 'Book 375', 'Book 868']

Enter fullscreen mode Exit fullscreen mode

To further understand the syntax of what makes a regular expression, I will provide resources at the end of this post!


Objects
For objects, we are going to sort this array by the object's id values

const users = [
 {id: 4, name: 'Jared' },
 {id: 8, name: 'Nicolette'},
 {id: 2, name: 'Michael'},
 {id: 5, name: 'Sade'},
 {id: 9, name: 'Megan'},
 {id: 1, name: 'Giovanni'},
]

const sorted = users.sort((a, b) => {
 return a.id - b.id 
})


console.log(sorted)

/*
 {id: 1, name: 'Giovanni'}
 {id: 2, name: 'Michael'}
 {id: 4, name: 'Jared'}
 {id: 5, name: 'Sade'}
 {id: 8, name: 'Nicolette'}
 {id: 9, name: 'Megan'}
*/
Enter fullscreen mode Exit fullscreen mode

Personal Note:
Regex is really cool but so far in my career I haven't personally used it. For the most part, I've seen people use regex to streamline algorithms and data type problems. If you use regex in your everyday tasks, let me know! I'd love to know how and resources you used to learn.

But for my beginners reading this, please don't fret. Try to absorb what you can but don't feel pressure to learn everything about regex! Just try to understand the breakdown of the regex used in the example.

Regex Resources:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes

https://www.computerhope.com/unix/regex-quickref.htm

. . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player