JavaScript Sort() Method Principles, Use-Cases, and Tasks

Now you will understand sorting in JavaScript.

JavaScript Sort() Method Principles, Use-Cases, and Tasks

Hey there ๐Ÿ‘‹.

In this article, you will learn the basic principles of the sort() array method in JavaScript, its use cases, along with some practical tasks at the end of the lesson.

Prerequisites

Before you continue with this tutorial, you should certify the following:

  1. That you know that the word array-method does exist in JavaScript.
  2. That you know the use of console.log() and function in JavaScript
  3. And, that you will read this article to the end ๐Ÿ˜€

So, without any further ado, let's get started


giphy (9).gif

Definition ๐Ÿ“š

The sort() method is one of the many array methods and it is very handy when you need to arrange elements of an array in either ascending, descending or in custom order without stress.

This arrangement can be implemented on numerics, alphabetical or emojis.


Syntax ๐Ÿ› 

The sort() array method is applied to an array using the following syntax.

1. Basic Sorting

array.sort()

By default, an array is sorted in ascending order when the sort method is applied to it.

2. Sorting in ascending order ๐Ÿ“ˆ

Another way to sort an array in ascending order (smallest to biggest) is to pass a callback function called the compare function into the sort() method.

array.sort(function(a, b){
return a - b
})

The compare function compares every element in the array using a and b as an instance of the elements currently been sorted in the array and they are arranged from smallest to the highest.

2. Sorting in descending order ๐Ÿ“‰

In order to sort elements of an array from the biggest to the smallest, the a-b expression is converted to b-a. This means that the highest elements (in strings) are compared to the smallest elements (in strings) and are therefore arranged in descending order.

array.sort(function(a, b){
return b - a
})

How it really works โ›‘

The sort() array method converts the elements of an array say numbers, emojis, characters, symbols, or strings into strings and compares them based on their order in the UTF-16 (16-bit).

Also:

  1. The sort() method arranges the elements in ascending order by default.
  2. The a-b expression arranges the smallest elements first
  3. The b-a expression arranges the biggest elements first
  4. The compare function is optional

Usecases ๐Ÿ’ฅ

Let's say we are given an unsorted array of random numbers, say [9, 3, 8, 7, 2]

const randomNumbers = [9, 3, 8, 7, 2];

Now let's log the values of the array variable randomNumbers in our browser console.

console.log (randomNumbers)

Expected Output ๐Ÿ‘‡

image.png


Tasks

Now that you've learned about the basics of the sort array method, go ahead and try out the tasks below to solve the use-cases.

1. Sort the randomNumbers array using the default sort() method

Expected output ๐Ÿ‘‡

image.png

2. Sort the randomNumbers array in ascending order using the compare function

Expected output ๐Ÿ‘‡

image.png

3. Sort the randomNumbers array in descending order using the compare function

Expected output ๐Ÿ‘‡

image.png


Custom Sorting

Congrats buddy๐Ÿธ, you have successfully learned how to sort an array of strings, emojis, or numbers in ascending and descending order, but what about an array of Objects? Let's get to it, here is what I mean ๐Ÿ‘‡

const studentsRecord = [
  {
    name: "Michael Jordan",
    score: 200,
  },
  {
    name: "Abraham Lincoln",
    score: 190,
  },
  {
    name: "Isreal Adesanya",
    score: 250,
  },
  {
    name: "Bill Gate",
    score: 140,
  },
];

In the above code snippet, we have an array of student objects containing the student name and score, now our job as a software developer is to make the teacher's job easier by building a simple program to help sort the students based on their score in two ways.

  1. Lowest-Highest Score
  2. Highest-Lowest Score

1. Sorting Lowest-Highest Score

In order to sort the student's records based on the lowest score to the highest score, we need to pass in the compare function and we are comparing based on the student's score property.

// Function that sort the lowest score first
const lowestFirst = (array) => {
  return array.sort((a, b) => {
    return a.score - b.score;
  });
};

// execute the function
console.log(lowestFirst(studentsRecord));

Expected Output ๐Ÿ‘‡

image.png

2. Sorting Highest-Lowest Score

As previously stated, in order to sort in descending order, we must change the a-b comparison expression to the b-a expression, as seen below ๐Ÿ‘‡.

// Function that sort the lowest score first
const highestFirst = (array) => {
  return array.sort((a, b) => {
    return b.score - a.score;
  });
};

// execute the function
console.log(highestFirst(studentsRecord));

Expected Output ๐Ÿ‘‡

image.png

Now the teacher is happy we will get paid ๐Ÿค‘ and can spend the weekend at the beach ๐Ÿ–

Note: The default sort() array method will not work in this case of array of object because we need to specify the property or basis we want to sort the array, so the comparison function must be included for this to be achievable.


Task โš’

Now that you've learned how to sort an array using a custom compare function, go ahead and attempt the task below.

You're a newly employed software engineer here on hashnode, and your first task is to sort out the most interacted blog posts for today in two methods on the landing page.

Methods ๐Ÿ‘‡

  1. In ascending order (less interacted blog post - most interacted blog post)
  2. In descending order (most interacted blog post - less interacted blog post)

~Posted Blog Post for the day

Formular ๐Ÿงฎ

likes + comments

const blogPosts = [
  {
    title: "how to center a div",
    likes: 122,
    comments: 4,
  },
  {
    title: "Learn javascript basics",
    likes: 190,
    comments: 40,
  },
  {
    title: "how to as questions",
    likes: 122,
    comments: 14,
  },
  {
    title: "Basic salary in silicon valley",
    likes: 142,
    comments: 2,
  },
  {
    title: "How to use vscode in 2020",
    likes: 1024,
    comments: 10,
  },
];

Good luck ๐Ÿ‘.


I'd love to see your solution, so feel free to share your solution in the comment section, and don't forget to take a break, drink water and exercise your legs, so it won't swell like mine ๐Ÿ˜‚.


Wow, what a journey, I am glad you made it to the end of this article, if you enjoyed and learned something new from this article, you can subscribe to my newsletter to get notified of my upcoming articles.

I will also like to connect with you, let's connect on:



See you in the next article. Bye Bye ๐Ÿ™‹โ€โ™‚๏ธ

image.png

If you found my content helpful and would want to support my blog, you can support me by buying me a coffee below, my blog lives on coffee ๐Ÿ™.