DEV Community

Cover image for Javascript Array Method - Sort()
Code Panda
Code Panda

Posted on • Updated on

Javascript Array Method - Sort()

In this blog, we’re going to explore the sort() javascript array method.

What does it do?

It changes the order of elements in your array and returns a new array with the sorted elements without changing your original array.

As always, let’s see an example…

const numbers = [5, 2, 7, 8, 4]

const newArr = numbers.sort()

console.log(newArr) // Output: [ 2, 4, 5, 7, 8 ]

In this example and the next few examples, we’re gonna explore the default behavior of the sort() method.

Here we see that it sorted our array in ascending order because we’re dealing with numbers.

What if we have a string array?

Example:

const animals = ["panda", "dog", "cat", "rabbit", "bear", "penguin", "wolf"]

const newArr = animals.sort()

console.log(newArr)

// Output: [ 'bear', 'cat', 'dog', 'panda', 'penguin', 'rabbit', 'wolf' ]

Here we’ll see that by default, it sorted our string array in alphabetical order.

But, what if we have some strings with uppercase letters?

const animals = ["panda", "dog", "cat", "Rabbit", "bear", "Penguin", "wolf"]

const newArr = animals.sort()

console.log(newArr)

// Output: [ 'Penguin', 'Rabbit', 'bear', 'cat', 'dog', 'panda', 'wolf' ]

Here we’ll see that it sorted the strings with the uppercase letter first, followed by the lowercase strings.

So far so good, now let’s mix together numbers with strings…

const animals = [
  "panda",
  "dog",
  2,
  "cat",
  "Rabbit",
  5,
  "bear",
  "Penguin",
  "wolf",
]

const newArr = animals.sort()

console.log(newArr)

Output: [ 2, 5, 'Penguin', 'Rabbit', 'bear', 'cat', 'dog', 'panda', 'wolf' ]

Now we’ll see that it sorted our array in the following order:

  1. Numbers ( in ascending order )
  2. Strings with an uppercase letter
  3. Lowercase strings

But, what if we have a more complex array? Let’s say an array containing some objects…

const developers = [
  { name: "John", age: 31, title: "Front-end developer", level: "Senior" },
  { name: "Lisa", age: 24, title: "Front-end developer", level: "Mid-senior" },
  { name: "Alex", age: 20, title: "Back-end developer", level: "Junior" },
  {
    name: "Sofia",
    age: 26,
    title: "Full-stack developer",
    level: "Mid-senior",
  },
]

const newArr = developers.sort()

console.log(newArr)

// Output:

// [{
//  name: 'John',
//     age: 31,
//     title: 'Front-end developer',
//     level: 'Senior' },

//   { name: 'Lisa',
//     age: 24,
//     title: 'Front-end developer',
//     level: 'Mid-senior' },

//   { name: 'Alex',
//     age: 20,
//     title: 'Back-end developer',
//     level: 'Junior' },

//   { name: 'Sofia',
//     age: 26,
//     title: 'Full-stack developer',
//     level: 'Mid-senior'
// }]

In this example, we have an array of developer objects.

Notice that by default, it didn’t change the order.

That is because there is a limitation to what it can sort by default.

In this case, we’ll need to specify our own logic and let it know how to sort this array.

We can do this by providing the sort() method a callback function which takes 2 parameters, usually called a and b.

Now, there are a few ways you can write your logic inside that callback function, one is writing a few if statements and focusing primarily on returning either true or false, or, you can write a shorthand version by writing a single line equation and focusing on either returning a positive number, a negative number or a zero. Which also can be looked at as true or false.

In this blog, we’ll focus on the shorthand syntax.

Let’s take a look once more at our developer’s array example and see how we can provide our own logic and sort it by the age of each developer.

const developers = [
  { name: "John", age: 31, title: "Front-end developer", level: "Senior" },
  { name: "Lisa", age: 24, title: "Front-end developer", level: "Mid-senior" },
  { name: "Alex", age: 20, title: "Back-end developer", level: "Junior" },
  {
    name: "Sofia",
    age: 26,
    title: "Full-stack developer",
    level: "Mid-senior",
  },
]

const newArr = developers.sort((a, b) => {
  return a.age - b.age
})

console.log(newArr)

// Output:

// [ { name: 'Alex',
//     age: 20,
//     title: 'Back-end developer',
//     level: 'Junior' },
//
//   { name: 'Lisa',
//     age: 24,
//     title: 'Front-end developer',
//     level: 'Mid-senior' },
//
//   { name: 'Sofia',
//     age: 26,
//     title: 'Full-stack developer',
//     level: 'Mid-senior' },
//
//   { name: 'John',
//     age: 31,
//     title: 'Front-end developer',
//     level: 'Senior' } ]

With this implementation, we managed to sort this array by age in ascending order.

Now let’s break down that callback function.

Parameters: a , b

a = first element in the array, which in this case is John.
b = second element in the array, which in this case is Lisa.

Function body:

As I mentioned earlier, we’ll need to focus on returning a positive number, a negative number or 0.

In the case of:

Positive: b will go before a
Negative: a will go before b
Zero: means they’re both equal so it’ll be treated as the same.

So Let’s take a look at the return value...

const newArr = developers.sort((a, b) => {
  // age of John ( 31 ) - age of Lisa ( 24 ) = 31 - 24 = 7
  return a.age - b.age
})

As specified in the comment, our return value will result in returning a positive value which is 7. That means that b will go before a, and if we take a look again at our array...

const developers = [
  { name: "John", age: 31, title: "Front-end developer", level: "Senior" },
  { name: "Lisa", age: 24, title: "Front-end developer", level: "Mid-senior" },
  { name: "Alex", age: 20, title: "Back-end developer", level: "Junior" },
  {
    name: "Sofia",
    age: 26,
    title: "Full-stack developer",
    level: "Mid-senior",
  },
]

Now, imagine b ( Lisa ) before a ( John ).

Since we’re sorting by age, so 24 before 31.

That will give us an idea of how the sorted array will look like. Since now, after imagining the new order of the first 2 elements, we have a lower number above a bigger number, so we can assume that it’ll sort the lower numbers above the bigger numbers which means in ascending order.

That’s exactly what we have if we look at our output again…

// Output:

// [ { name: 'Alex',
//     age: 20,
//     title: 'Back-end developer',
//     level: 'Junior' },
//
//   { name: 'Lisa',
//     age: 24,
//     title: 'Front-end developer',
//     level: 'Mid-senior' },
//
//   { name: 'Sofia',
//     age: 26,
//     title: 'Full-stack developer',
//     level: 'Mid-senior' },
//
//   { name: 'John',
//     age: 31,
//     title: 'Front-end developer',
//     level: 'Senior' } ]

Now, if we want them in the opposite order ( descending order ) we can just switch to ( b - a ) in instead of ( a - b ) and that will result in a negative return value so, from the rules above, this will result in having a before b.

const newArr = developers.sort((a, b) => {
  // age of Lisa ( 24 ) - age of John ( 31 ) = 24 - 31 = -7
  return b.age - a.age
})

// Rules:

// Positive: b will go before a
// Negative: a will go before b
// Zero: That means they’re both equal to it’ll be treated as the same.

Hopefully, you understood my explanation.

If you didn’t, consider watching my video on this topic.

But...

If you learned something new...

Consider sharing this blog with someone whom you think might benefit from it.

As always, have a great day! 😇

Top comments (0)