JavaScript Sort: A Complete Guide to Array Sorting

Learn how to sort arrays of strings, numbers, and objects in JavaScript. Master the sort() method with practical examples and best practices for modern web development.

Understanding the JavaScript sort() Method

The sort() method is a built-in Array method in JavaScript that arranges the elements of an array in a specified order. Unlike other array methods that return new arrays, sort() modifies the original array in place and returns a reference to the same array.

Default Behavior

The default behavior of sort() is to arrange elements as strings in ascending order, based on UTF-16 code unit values. This means that when you sort an array of strings, they're arranged alphabetically from A to Z.

Key Point: This string-based sorting can produce unexpected results when working with numbers, since "10" comes before "2" in string comparison.

For more details on how JavaScript handles comparisons, see the MDN documentation on Array.prototype.sort().

Basic sort() Syntax
1// Without compare function (string sorting)2const fruits = ['Banana', 'Apple', 'Cherry', 'Date'];3fruits.sort();4console.log(fruits);5// Output: ['Apple', 'Banana', 'Cherry', 'Date']6 7// With compare function (numeric sorting)8const numbers = [1, 30, 4, 21, 100000];9numbers.sort((a, b) => a - b);10console.log(numbers);11// Output: [1, 4, 21, 30, 100000]

Sorting Strings

When you call sort() on an array of strings, JavaScript arranges them alphabetically by default. This works well for most use cases involving text data.

Case-Insensitive Sorting

The default string sorting is case-sensitive, meaning uppercase letters are sorted before lowercase letters. To sort strings regardless of their case, use localeCompare() which provides sophisticated string comparison capabilities:

const names = ['alice', 'Bob', 'charlie', 'Alice'];
names.sort((a, b) => a.localeCompare(b));
// Output: ['alice', 'Alice', 'Bob', 'charlie'] - case-insensitive

The localeCompare() method is particularly valuable because it respects locale-specific ordering rules and handles accented characters intelligently. This is essential when building internationalized web applications that serve users across different regions and languages. Understanding how string methods work together helps you build more robust data handling pipelines.

Sorting Numbers

Important: Sorting numbers requires a compare function because the default string-based sorting doesn't work as expected.

Without a compare function: [1, 30, 4, 21, 100000].sort() produces [1, 100000, 21, 30, 4] because each number is converted to a string first.

Ascending vs Descending Order

  • Ascending: (a, b) => a - b
  • Descending: (a, b) => b - a

Understanding these patterns is fundamental to working with JavaScript arrays effectively in your web applications. For more complex data transformations, combining sort with JSON parsing helps you prepare data for display.

Numeric Sorting Examples
1// Ascending order2const numbers = [1, 30, 4, 21, 100000];3numbers.sort((a, b) => a - b);4console.log(numbers);5// Output: [1, 4, 21, 30, 100000]6 7// Descending order8const numbers2 = [1, 30, 4, 21, 100000];9numbers2.sort((a, b) => b - a);10console.log(numbers2);11// Output: [100000, 30, 21, 4, 1]

Sorting Arrays of Objects

In modern web development, you frequently work with arrays of objects. To sort by an object property, access that property in your compare function.

Basic Object Property Sorting

Use localeCompare() for string properties and subtraction for numeric properties:

const products = [
 { name: 'Laptop', price: 999 },
 { name: 'Phone', price: 599 },
 { name: 'Tablet', price: 399 }
];

// Sort by price ascending
products.sort((a, b) => a.price - b.price);
// Output: Tablet ($399), Phone ($599), Laptop ($999)

Multiple Property Sorting

Chain comparisons when sorting by multiple criteria. This technique is commonly used in e-commerce web development for product filtering and sorting features. When working with dynamic data, you might also use queryselector to gather elements and then sort them programmatically.

Sorting Objects by Multiple Properties
1// Multi-property sorting: category first, then price2const items = [3 { name: 'Apple', category: 'fruit', price: 1 },4 { name: 'Carrot', category: 'vegetable', price: 1 },5 { name: 'Banana', category: 'fruit', price: 2 }6];7 8items.sort((a, b) => {9 const categoryResult = a.category.localeCompare(b.category);10 if (categoryResult !== 0) return categoryResult;11 return a.price - b.price;12});13// Sorted by category, then by price within each category

Sorting Dates

Date sorting requires converting date strings into comparable values using the Date constructor:

const events = [
 { name: 'Event A', date: '2023-01-01' },
 { name: 'Event B', date: '2022-12-31' },
 { name: 'Event C', date: '2023-06-15' }
];

events.sort((a, b) => new Date(a.date) - new Date(b.date));
// Output: Event B (Dec 31), Event A (Jan 1), Event C (Jun 15) - chronological order

This approach is essential for building event calendars, activity feeds, and dynamic web applications that display time-based content. Combined with array methods like filter and map, you can build powerful data manipulation pipelines.

Best Practices and Common Pitfalls

The In-Place Modification

The sort() method modifies the original array. If you need to preserve the original order, create a copy first:

const original = [3, 1, 4, 1, 5];
const sorted = [...original].sort((a, b) => a - b);
// original remains: [3, 1, 4, 1, 5]
// sorted becomes: [1, 1, 3, 4, 5]

Using the spread operator to create a copy is essential for maintaining immutable data patterns in modern JavaScript frameworks like React.

Handling Edge Cases

  • undefined and null values are placed at the end
  • Handle missing properties with default values using logical OR (||)
  • Keep compare functions simple for better performance

Quick Reference

Data TypeAscendingDescending
Stringsa.localeCompare(b)b.localeCompare(a)
Numbersa - bb - a
Objectsa.prop - b.propb.prop - a.prop
Datesnew Date(a) - new Date(b)new Date(b) - new Date(a)

Frequently Asked Questions

Does sort() create a new array?

No, sort() modifies the original array in place and returns a reference to the same array. Use the spread operator [...array] to create a copy before sorting if needed.

Why is 10 sorted before 2?

Without a compare function, elements are converted to strings. In string comparison, "10" comes before "2" because the character "1" has a lower UTF-16 code unit value than "2".

What's the difference between localeCompare and simple comparison?

localeCompare() provides locale-aware string comparison, handling accented characters and language-specific ordering rules correctly. Simple comparison uses UTF-16 code unit values directly.

How do I sort without modifying the original array?

Create a copy using the spread operator: [...array].sort((a, b) => a - b). This preserves your original array while returning a sorted copy.

Master JavaScript for Modern Web Development

Our team builds performant, scalable web applications using the latest JavaScript techniques and best practices.