Back to JavaScript
2026-03-278 min read

JS Array Sort (JavaScript)

Learn JS Array Sort (JavaScript) step by step with clear examples and exercises.

Why This Matters

Array sorting is a fundamental concept in programming that helps organize data efficiently. In this lesson, we'll delve into how to sort arrays using JavaScript, a popular and versatile scripting language. By the end of this tutorial, you'll be able to tackle real-world problems involving array sorting with confidence.

Sorting arrays is crucial in various scenarios:

  1. Organizing data in a logical order for easier analysis
  2. Improving search efficiency by reducing the number of comparisons
  3. Ensuring that data structures are stable during sorting (i.e., preserving relative positions of equal elements)
  4. Debugging algorithms to identify performance bottlenecks
  5. Preparing for technical interviews where array sorting questions are common
  6. Streamlining code by automatically organizing data in the correct order
  7. Enhancing user experience by presenting sorted results in a logical manner
  8. Facilitating data analysis and visualization by providing well-organized datasets
  9. Implementing efficient search algorithms that require sorted arrays as input
  10. Optimizing database queries for faster response times

Prerequisites

To follow this tutorial, you should have a basic understanding of:

  1. JavaScript syntax and variables (e.g., let, const)
  2. Data structures in JavaScript (e.g., arrays, objects)
  3. Basic control flow statements (e.g., if, else, for, while)
  4. Functions in JavaScript (including function declarations and arrow functions)
  5. Understanding the concept of sorting algorithms
  6. Familiarity with common data structures such as linked lists, stacks, queues, and trees
  7. Basic understanding of Big O notation to analyze the time complexity of algorithms
  8. Knowledge of JavaScript ES6 features (optional but recommended)

Core Concept

Sorting Algorithms

Before diving into array sorting with JavaScript, let's briefly discuss some popular sorting algorithms:

  1. Bubble Sort: Simple but inefficient for large datasets. It repeatedly compares adjacent elements and swaps them if they are out of order. Its time complexity is O(n^2) in the worst case.
  1. Selection Sort: Slightly more efficient than bubble sort. It finds the smallest element from the unsorted part of the array and places it at the beginning. Its time complexity is O(n^2) in the worst case.
  1. Insertion Sort: Efficient for small datasets but inefficient for large ones. It builds a sorted array by inserting elements one-by-one into their correct positions within an already sorted subarray. Its time complexity is O(n^2) in the worst case.
  1. Merge Sort: A divide-and-conquer algorithm that recursively divides the input array into smaller subarrays until each subarray contains only a single element, then merges them back together in sorted order. Its time complexity is O(n log n).
  1. Quick Sort: Another divide-and-conquer algorithm that partitions the array around a pivot element and recursively sorts both halves. It is generally more efficient than merge sort for larger datasets, with a time complexity of O(n log n) in the average case and O(n^2) in the worst case.
  1. Heap Sort: A comparison-based sorting algorithm that builds a binary heap and sorts elements by repeatedly removing the largest or smallest element from the heap. Its time complexity is O(n log n).
  1. Radix Sort: An efficient sorting algorithm for large datasets with integers as input, based on the number of digits in each integer. Its time complexity is O(nk), where n is the number of elements and k is the maximum number of digits.

Built-in Array Sort Function

Fortunately, JavaScript provides a built-in sort() method to handle array sorting, so you don't have to implement these algorithms yourself. The sort() function sorts the elements of an array in place and returns the sorted array. By default, it sorts the elements as strings in Unicode code point order.

let numbers = [34, 15, 88, 2];
numbers.sort(); // [2, 15, 34, 88]

To sort numbers as actual numbers, you can pass a comparison function to the sort() method:

let numbers = [34, 15, 88, 2];
numbers.sort((a, b) => a - b); // [2, 15, 34, 88]

Custom Sorting Functions

In some cases, you may need to customize the sorting behavior by providing your own comparison function. For example, if you want to sort an array of objects based on a specific property:

let people = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
{ name: 'Mike', age: 20 }
];

people.sort((a, b) => a.age - b.age); // Sorts people by age in ascending order

Worked Example

Let's sort an array of mixed data types and customize the sorting behavior:

let mixedData = ['apple', 'banana', 3, 'orange', 5];
mixedData.sort((a, b) => {
// Compare strings first
if (typeof a === 'string' && typeof b === 'string') {
return a.localeCompare(b);
}

// Then compare numbers
if (typeof a === 'number' && typeof b === 'number') {
return a - b;
}

// If types are different, maintain the original order
return 0;
});

After sorting, mixedData will be:

['apple', 'banana', 3, 'orange', 5] // Unsorted array
['apple', 'banana', 3, 'orange', 5] // Sorted as strings (incorrect)
['apple', 'banana', 3, 'orange', 5] // Sorted as numbers (correct)

To sort the array first by strings and then by numbers, you can modify the comparison function:

let mixedData = ['apple', 'banana', 3, 'orange', 5];
mixedData.sort((a, b) => {
// Compare strings first
if (typeof a === 'string' && typeof b === 'string') {
return a.localeCompare(b);
}

// If types are the same, compare numbers
if (typeof a === 'number' && typeof b === 'number') {
return a - b;
}

// If types are different, maintain the original order
return 0;
});

After sorting, mixedData will be:

['apple', 'banana', 3, 'orange', 5] // Unsorted array
['apple', 'banana', 3, 'orange', 5] // Sorted as strings (incorrect)
['apple', 'banana', 3, 'orange', 5] // Sorted as numbers (correct)
['apple', 'orange', 'banana', 3, 5] // Sorted first by strings and then by numbers

Common Mistakes

  1. Not providing a comparison function: When sorting numbers, always pass a comparison function to the sort() method to ensure they are sorted as numbers, not strings.
  1. Inconsistent data types: If your array contains both strings and numbers, you'll need to provide a custom comparison function that can handle both cases.
  1. Misunderstanding the default sort order: By default, JavaScript sorts arrays in Unicode code point order when dealing with strings. This may not always produce the expected results.
  1. Sorting in-place: The sort() method modifies the original array, so be careful when using it on critical data structures. If you need to preserve the original array, create a copy before sorting.
  1. Overcomplicating custom comparison functions: Focus on comparing elements based on their types and values, and avoid unnecessary complexity in your comparison function.
  1. Ignoring edge cases: Be aware of potential edge cases such as null or undefined values, empty strings, and objects with identical properties when creating custom comparison functions.
  1. Not considering the time complexity of custom sorting functions: Custom sorting functions can have a significant impact on performance, so be mindful of their time complexity and optimize them where possible.

Practice Questions

  1. Write a function that sorts an array of strings in lexicographical order (i.e., alphabetical order).
  1. Given an array of integers, write a function that sorts them in descending order using the built-in sort() method.
  1. Given an array of mixed data types, write a function that sorts it first by strings and then by numbers.
  1. Write a custom comparison function for sorting an array of objects based on their properties.
  1. Write a function that sorts an array of arrays (i.e., a multidimensional array) based on the values in the first element of each subarray.
  1. Given an array of strings, write a function that sorts them in reverse lexicographical order (i.e., alphabetical order but in descending order).
  1. Write a custom comparison function for sorting an array of objects based on multiple properties.
  1. Write a function that sorts an array of dates in chronological order.
  1. Given an array of arrays, write a function that merges the arrays into one sorted array.
  1. Write a function that sorts an array of objects based on a custom scoring system (e.g., sorting by total points earned in a game).

FAQ

Q: Why does JavaScript sort strings differently than other languages?

A: JavaScript sorts strings in Unicode code point order, which takes into account the characters' positions in the Unicode standard. This can lead to unexpected results when comparing strings that contain non-ASCII characters or symbols.

Q: Is it possible to sort an array without modifying its original contents?

A: Yes, you can create a copy of the array before sorting and then return the sorted copy. Alternatively, you can use the slice() method to create a new array and sort that instead.

Q: What's the time complexity of the built-in JavaScript sort function?

A: The built-in JavaScript sort function uses a modified merge sort algorithm with a worst-case time complexity of O(n log n). However, it may be optimized for smaller arrays and use a different algorithm (like quicksort) in some cases.

Q: Can I customize the sorting behavior for specific data types or properties?

A: Yes, you can provide a custom comparison function to the sort() method, which allows you to customize the sorting behavior based on your needs.

Q: What's the best sorting algorithm for large datasets in JavaScript?

A: For large datasets, quicksort is generally more efficient than merge sort in JavaScript. However, the actual performance may vary depending on the specific dataset and implementation details.

Q: Can I use other sorting algorithms besides bubble sort, selection sort, insertion sort, merge sort, and quicksort in JavaScript?

A: Yes, you can implement other sorting algorithms in JavaScript, such as heap sort, radix sort, or counting sort, depending on your specific requirements.

JS Array Sort (JavaScript) | JavaScript | XQA Learn