paint-brush
Sorting an Array in JavaScript: A Beginner's Guideby@rahull
153 reads

Sorting an Array in JavaScript: A Beginner's Guide

by RahulFebruary 27th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

The Javascript array sort() method is an incredibly powerful tool that makes it easy to organize and manipulate data in almost any way imaginable. To use this method, all you have to do is call the function with two optional arguments - a "compare" function and a "options" object. With just a few lines of code, you can quickly start sorting arrays with ease.
featured image - Sorting an Array in JavaScript: A Beginner's Guide
Rahul HackerNoon profile picture

If you've ever needed to get something in order, the first thought that comes to mind is often, "let's sort this out!" And with JavaScript, that sentiment remains true.


A great way to quickly rearrange data is by using the Array sort() method.


Whether you're a beginner or a pro programmer, it's important to understand how the Array sort() function works in JavaScript.


In this guide, we'll give you a detailed overview of what the sort() function does and how it can help you arrange data quickly and easily.


We'll cover topics such as sorting arrays of strings, numbers, and objects, as well as discuss the different types of sorting algorithms available and when to use them.


So, let's get started on our journey into the world of JavaScript sort()!

Overview of Javascript array Sort()

Are you looking for a way to sort your array in Javascript? The Javascript sort() method can be a great tool for organizing your data so that you can quickly and easily make changes to it.


This guide will provide you with an overview of the Javascript array sort() method and how it can help you organize your data.


Using the sort() method, you can take an array of objects and rearrange them alphabetically, numerically, or according to any custom criteria.


To use this method, all you have to do is call the function with two optional arguments - a "compare" function and a "options" object.


The options object lets you specify how to sort the array - ascending or descending order, for example - while the compare function lets you define custom sorting logic.


Simply put, the Javascript array sort() method is an incredibly powerful tool that makes it easy to organize and manipulate data in almost any way imaginable.


With just a few lines of code, you can quickly start sorting arrays with ease.


So if you're looking for an efficient way to manage your data, Javascript's sort() method is worth checking out!

Best Practices for Sorting Javascript Arrays

If you're ready to start sorting your Javascript arrays, there are a few best practices to keep in mind. Every situation is unique, and your code will depend on the values you're working with and the outcome you're trying to achieve.


However, here are a few best practices for Javascript array sort() that will help get you started:


  • Make sure to look over your array before sorting it:


It's important to double-check everything before initiating the sort(). This way, you can make sure that there are no duplicate values, invalid data types, or empty strings that could potentially cause the sort() process to fail.


  • Understand the different methods of sorting:


When it comes to javascript array sort(), there are a number of different methods available for use depending on your needs. Some of the most popular options include sort()reverse()splice() and slice().


  • Consider using a callback function:


Callback functions can be incredibly helpful when using a javascript array sort(). These functions allow you to define custom sorting criteria when sorting complex objects or arrays with multiple values.


It's important to keep in mind that callback functions have performance implications and should be used cautiously.

How to Sort Javascript Arrays With Sort()

To use the sort () method, pass a function that defines the pattern for sorting objects in the array. This can be as simple as sorting strings in alphabetical order or as complex as sorting arrays of objects by a certain attribute.


For example, if you wanted to sort an array of objects by a user name, you could use:


array.sort((a, b) => {
    const nameA = a.userName.toUpperCase();
    const nameB = b.userName.toUpperCase();

    if (nameA < nameB) {
        return -1;
    }

    if (nameA > nameB) {
        return 1;
    }

    return 0;
});

How to Sort Array Numbers With Sort()

You can also use the sort() method to sort an array of numbers by ascending or descending order.


To sort an array in ascending order, you will need to pass a function as an argument that tells sort() how to compare two elements within the array.


A common way to do this is with a custom function that takes two parameters, a and b, and performs a comparison between them. You can use the > (greater than) or < (less than) operators to determine what order the elements should be in.


If you want the array sorted in ascending order, you should return a value greater than 0 if a > b, and less than 0 if a < b.

How to Sort Numbers With Sort()

Here’s an example of how to sort an array of numbers:

	let numbers = [9, 10, 3, 4];
	numbers.sort(function (a, b) {
	return a - b;
  });

// Example
console.log(numbers); // Logs [3, 4, 9, 10]


The code first creates an array called “numbers” with four elements inside, it then uses the sort() method on this array.


We pass a custom function as a parameter that takes two parameters “a” and “b” and performs a comparison between them using the less-than operator ( < ) which returns true if “a” is less than “b” otherwise false.


The values returned from our custom function determine what order

How to Sort an Array of Objects With Sort()

To sort an array of objects in JavaScript, you can use the sort() method of the array and pass a comparison function as an argument.


The comparison function should take two objects from the array as arguments and return a negative number, 0, or a positive number depending on whether the first object should come before, equal to, or after the second object in the sorted array.

const students = [
  { name: 'Alice', grade: 90 },
  { name: 'Bob', grade: 80 },
  { name: 'Charlie', grade: 95 },
  { name: 'David', grade: 85 }
];

students.sort((student1, student2) => student2.grade - student1.grade);

console.log(students);
// Output: [
//   { name: 'Charlie', grade: 95 },
//   { name: 'Alice', grade: 90 },
//   { name: 'David', grade: 85 },
//   { name: 'Bob', grade: 80 }
// ]


In this example, we have an array of objects representing students with their names and grades.


We want to sort the array in descending order of grade, so we pass a comparison function to sort() that takes two students and subtracts their grades (student2.grade - student1.grade).


If the result is negative, it means that the first student has a higher grade and should come before the second student in the sorted array.


If the result is positive, it means that the second student has a higher grade and should come before the first student.


If the result is zero, it means that the students have the same grade, and their order doesn't matter.

How to Sort an Array of Strings With Sort()

By default, sort() sorts the elements of an array in ascending order based on their Unicode values. That means that uppercase letters come before lowercase letters, and numbers come before letters.


However, you can provide a custom sorting function to sort() to define your own sorting technique.

const fruits = ['banana', 'apple', 'orange', 'pineapple'];
fruits.sort(); // ['apple', 'banana', 'orange', 'pineapple']

console.log(fruits);


In this example, the fruits array is sorted in ascending order based on the default sorting technique.


If you want to sort an array of strings in descending order, you can provide a custom sorting function to sort():


const fruits = ['banana', 'apple', 'orange', 'pineapple'];
fruits.sort((a, b) => b.localeCompare(a)); // ['pineapple', 'orange', 'banana', 'apple']

console.log(fruits);


In this example, the sort() method is called with a custom sorting function that uses the localeCompare() method to compare two strings.


The localeCompare() method returns a negative value if a should come before b, a positive value if a should come after b, and 0 if a and b are equal.


By reversing the order of a and b, we can sort the array in descending order.


Different Sort Methods in Javascript

If you're getting started with javascript array sort(), you can learn about the different sorting methods available. There are different kinds of sorting algorithms, and each one offers something depending on what you're trying to accomplish.


Below is a breakdown of the different sorting methods and when you should use each one.

Bubble Sort

Bubble sort is one of the simplest sorting algorithms available in JavaScript. It's an algorithm that compares two adjacent elements in an array, and then swaps their positions if the order is wrong.


This algorithm is good for small datasets, but it's not recommended for large ones because it's very slow.


function bubbleSort(arr) {
  var len = arr.length;
  for (var i = 0; i < len - 1; i++) {
    for (var j = 0; j < len - 1 - i; j++) {
      if (arr[j] > arr[j + 1]) {
        var temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
      }
    }
  }
  return arr;
}

// Example 
var myArray = [5, 3, 1, 4, 2];
var sortedArray = bubbleSort(myArray);
console.log(sortedArray); // [1, 2, 3, 4, 5]

Insertion Sort

Insertion sort orders items by iterating over subarrays until all elements are sorted in the right order. This type of sort is faster than bubble sort and works well with small datasets or already partially-sorted arrays.


It's also relatively easy to understand, making it a great option for beginners.


function insertionSort(arr) {
  for (let i = 1; i < arr.length; i++) {
    let current = arr[i];
    let j = i - 1;
    while (j >= 0 && arr[j] > current) {
      arr[j + 1] = arr[j];
      j--;
    }
    arr[j + 1] = current;
  }
  return arr;
}

// Example
const arr = [5, 1, 3, 6, 4, 2];
console.log(insertionSort(arr)); // [1, 2, 3, 4, 5, 6]

Selection Sort

Selection sort works by selecting the smallest element from an unsorted array and putting it at its correct position within the array.


It does this by looping through the array, finding the smallest element, and swapping it with its current position until all elements are sorted correctly.


This type of sort algorithm can be faster than other methods, especially if there are a lot of duplicate elements in an array.


function selectionSort(arr) {
  for (let i = 0; i < arr.length - 1; i++) {
    let minIndex = i;
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[j] < arr[minIndex]) {
        minIndex = j;
      }
    }
    if (minIndex !== i) {
      let temp = arr[i];
      arr[i] = arr[minIndex];
      arr[minIndex] = temp;
    }
  }
  return arr;
}

// Example
const arr = [5, 3, 6, 2, 7];
const sortedArr = selectionSort(arr);
console.log(sortedArr); // [2, 3, 5, 6, 7]

Merge Sort

Merge sort is a powerful sorting algorithm that can be used to quickly and efficiently sort large datasets.


It works by splitting an array into individual subarrays, sorting each of them, and then combining them back together in the correct order.


It's a recursive algorithm, meaning that it calls itself multiple times with smaller input each time, so it can be quite slow when dealing with large data.


Merge sort is fairly easy to understand and provides a great balance between performance and efficiency.


Read more about merge sort -> https://stackabuse.com/merge-sort-in-javascript/


You'll see me writing more on these algorithms and explaining them bit by bit in a very simple way in upcoming blog posts.


Conclusion

In short, the Javascript sort() method is an incredibly useful way to organize an array, whether you’re sorting numbers, strings, or objects.


The sorting process is really easy to implement and understand, but it’s important to have a general understanding of the function so you can get the most out of it.


There are a lot of options and customizations to the array sort in JavaScript, so be sure to take full advantage of all it has to offer.


So now that you know the basics of arguably the most important method in all of JavaScript, you’re ready to build powerful and efficient websites and apps.


Hustle!


Read More in JavaScript