Sorting Arrays in JavaScript
Tags: javascript, beginners, tutorial, webdev
Published: 2022-06-01 21:00:30

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. 

---


<u>Strings</u>
The sort method by default organizes its elements alphabetically. 

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

const sortNames = names.sort()

console.log(sortNames)

//['Cooper', 'Emmy', 'Fletcher', 'Izzy', 'Sophie']
```

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

```JavaScript
const reversedNames = sortNames.reverse()

console.log(reversedNames)

// ['Sophie', 'Izzy', 'Fletcher', 'Emmy', 'Cooper']
```


---


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

```JavaScript
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]

```

---


<u>Strings with Numbers</u>
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. 

```JavaScript
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']
```

---


<u>Strings with Long Numbers</u>
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:


```JavaScript

const coolRegex = /\d+/

```

- 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:

```JavaScript

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']

```

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


---


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

```JavaScript
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'}
*/
```

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