DEV Community

Melissa Guachun
Melissa Guachun

Posted on

Sorting Arrays in JavaScript

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

Top comments (7)

Collapse
 
chrisgreening profile image
Chris Greening • Edited

These days I use regex a lot in pattern matching column names while processing data!

Quite often I'm combining dozens of different datasets and generating hundreds of new attributes along the way to feed into our models so there'll be a lot of columns with similar names i.e. clicks_A, clicks_B, clicks_C, etc. that I want to dynamically access so I'd use regex to select all columns prefixed with "clicks" in the column name, etc.

In the past I worked on a gig extracting text data from semistructured OCR scanned PDFs and transforming the data into spreadsheets. I used regex a ton then for writing fuzzy string searching algos (it was more of a nightmare than it sounds 😅)

I've picked up a bit of regex along the way just from exposure and necessity but I still frequently use RegExr to test patterns against some raw test data

And come to think of it I use grep literally everyday and occasionally sed/whatever other offhand commands while bash'ing some automation scripts!

Great article Melissa!!!!

Collapse
 
melguachun profile image
Melissa Guachun

That's so cool!!! That's such a great resource, I feel like it's hard to really understand if regex is doing it's job unless you're able to test it! I feel like it's so useful but I really didn't get that much exposure to it at my coding bootcamp. Aw, thanks friend, and thanks for sharing Chris!

Collapse
 
tqbit profile image
tq-bit • Edited

Great article on sorting. I used to struggle with understanding sorting and how it works quite a bit when learning JS.

About Regex: ihateregex.io/. Describes my feelings towards - and solves most of my problems with - regular expressions pretty well.

Collapse
 
melguachun profile image
Melissa Guachun

I love the site name hahaha thank you for sharing, I'll explore this site more!!

Collapse
 
andrewbaisden profile image
Andrew Baisden

These are great snippets thanks.

Collapse
 
melguachun profile image
Melissa Guachun

Thanks Andrew, hope they help!

Collapse
 
sajadssa profile image
sajad

supper appreciate,keep going