JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS Array Sort


Sorting arrays is a common requirement in JavaScript, whether you need to display a list of names alphabetically, organize numbers from lowest to highest, or sort objects based on specific properties. JavaScript provides built-in methods to sort arrays efficiently, giving developers the flexibility to handle both simple and complex sorting tasks.

This tutorial covers the fundamentals of array sorting, including default sorting behavior, numeric and custom sorting, sorting objects, practical examples, common mistakes, and best practices.

Why Array Sorting Is Important

Sorting is essential because it allows you to:

  • Display data in a logical or readable order

  • Compare and rank items

  • Improve user experience in lists and tables

  • Perform calculations that rely on ordered data

  • Prepare data for search, filtering, or reporting

Without proper sorting, managing and interpreting data can become confusing and error-prone.

Default Sorting Behavior

The sort() method is used to sort the elements of an array in place. By default, sort() converts elements to strings and sorts them in ascending Unicode code point order.

let fruits = ["Banana", "Apple", "Cherry"];
fruits.sort();
console.log(fruits); // ["Apple", "Banana", "Cherry"]

Sorting Numbers

Sorting numbers with the default sort() may give unexpected results because elements are treated as strings:

let numbers = [40, 100, 1, 5];
numbers.sort();
console.log(numbers); // [1, 100, 40, 5] - not numeric order

To sort numbers correctly, you must provide a compare function.

Numeric Sorting with Compare Function

The compare function receives two arguments, a and b. It should return:

  • A negative value if a should come before b

  • Zero if they are equal

  • A positive value if a should come after b

Ascending Order

numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 5, 40, 100]

Descending Order

numbers.sort((a, b) => b - a);
console.log(numbers); // [100, 40, 5, 1]

Sorting Strings

Strings are sorted alphabetically by default. You can also use a compare function for case-insensitive sorting:

let names = ["emma", "Lily", "Sophia", "olivia"];
names.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
console.log(names); // ["emma", "Lily", "olivia", "Sophia"]

Using localeCompare()

localeCompare() is useful for sorting strings according to local language rules:

let words = ["résumé", "apple", "zebra"];
words.sort((a, b) => a.localeCompare(b));
console.log(words); // ["apple", "résumé", "zebra"]

Sorting Arrays of Objects

When working with arrays of objects, sorting by a property is common:

let students = [
  { name: "Emma", score: 85 },
  { name: "Lily", score: 92 },
  { name: "Sophia", score: 78 }
];

// Sort by score ascending
students.sort((a, b) => a.score - b.score);
console.log(students);

// Sort by name alphabetically
students.sort((a, b) => a.name.localeCompare(b.name));
console.log(students);

Reversing an Array

The reverse() method reverses the order of elements. It is often used in combination with sort():

let numbers = [1, 2, 3, 4, 5];
numbers.reverse();
console.log(numbers); // [5, 4, 3, 2, 1]

Practical Examples

Example 1: Sorting a List of Names

let students = ["Olivia", "Emma", "Sophia", "Lily"];
students.sort();
console.log(students); // ["Emma", "Lily", "Olivia", "Sophia"]

Example 2: Sorting Numbers Numerically

let scores = [45, 78, 90, 60];
scores.sort((a, b) => a - b); // ascending
console.log(scores); // [45, 60, 78, 90]

Example 3: Sorting Numbers Descending

scores.sort((a, b) => b - a);
console.log(scores); // [90, 78, 60, 45]

Example 4: Sorting Objects by Property

let products = [
  { name: "Shirt", price: 25 },
  { name: "Shoes", price: 50 },
  { name: "Hat", price: 15 }
];

products.sort((a, b) => a.price - b.price);
console.log(products);

Example 5: Case-Insensitive String Sorting

let names = ["emma", "Lily", "Sophia", "olivia"];
names.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
console.log(names); // ["emma", "Lily", "olivia", "Sophia"]

Example 6: Sorting and Reversing

let numbers = [10, 5, 40, 100];
numbers.sort((a, b) => a - b).reverse();
console.log(numbers); // [100, 40, 10, 5]

Common Mistakes

  • Using sort() on numbers without a compare function.

  • Assuming sort() returns a new array; it sorts in place.

  • Forgetting that localeCompare() is needed for proper alphabetical order with special characters or case-insensitive sorting.

  • Attempting to sort objects without specifying a property.

Best Practices

  • Always use a compare function when sorting numbers.

  • Use localeCompare() for strings when case-insensitive or language-specific sorting is required.

  • Remember that sort() modifies the original array; create a copy if the original array must remain unchanged.

  • Chain sort() with reverse() only when needed and keep code readable.

  • When sorting complex objects, clearly define the property and comparison logic.

Summary of JS Array Sort

The sort() method in JavaScript is a powerful tool for ordering arrays, whether they contain strings, numbers, or objects. Understanding the default behavior, using compare functions for numeric and object sorting, and leveraging methods like localeCompare() and reverse() allows developers to manage data effectively. Correctly implementing array sorting ensures that applications display organized, readable, and meaningful information, which is crucial for user experience, reporting, and data analysis.


Practice Questions

Q1. How do you sort an array of fruits alphabetically?

Q2. What happens when you use sort() on numbers without a compare function?

Q3. How do you sort an array of numbers in ascending order?

Q4. Which function is passed to sort() to reverse the order of numbers?

Q5. How do you sort an array of names in descending alphabetical order?

Q6. What method do you use to sort and then reverse the order of the array?

Q7. How can you sort an array of objects by their age property in increasing order?

Q8. Which method helps sort an array of objects alphabetically by name?

Q9. How do you sort the array [100, 2, 50, 10] in descending order correctly?

Q10. What is the output of ["z", "a", "m"].sort()?


Try a Short Quiz.

No quizzes available.


Online Code Editor and Compilor

Write and run code directly in your browser. Live preview for frontend languages.


JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top