Array sort javascript: A Practical Guide to Sorting JavaScript Arrays

Master array sort javascript with practical techniques: numeric and string sorting, locale-aware comparisons, and multi-criteria sorts for reliable in-place JavaScript arrays.

JavaScripting
JavaScripting Team
·5 min read
Sort Arrays in JS - JavaScripting
Quick AnswerDefinition

Array sort javascript uses the built-in sort method to order elements in an array. By default, it converts elements to strings and sorts lexicographically, which can yield surprising results for numbers. To sort numbers or objects reliably, pass a comparator function, such as (a,b)=>a-b for ascending numeric order. You can also use localeCompare for locale-aware strings.

What array sort javascript does and default behavior

In JavaScript, sorting arrays is a common task, but many developers underestimate how Array.prototype.sort actually works. The method sorts the elements of an array in place, meaning it mutates the original array rather than returning a new one. The default behavior is to convert every element to a string and compare those strings in lexicographic order. This means numbers can end up out of order if you rely on the default behavior alone. For example, consider the array [3, 1, 4, 2, 10]. Calling sort() without a comparator produces [1, 10, 2, 3, 4], because "1" < "10" < "2" in string terms. See how surprising that can be?

To avoid this, always supply a comparator function that returns a number indicating sort order. A comparator receives two arguments, a and b, and should return a negative value if a should come before b, a positive value if after, and zero if equal. The simplest numeric comparator is (a,b)=>a-b for ascending order. The effect is predictable, repeatable, and independent of the elements' types, as long as the comparator handles them correctly. In this section you will experiment with default behavior, then move to numeric and string comparisons.

JavaScript
// Default sort: elements are converted to strings const nums = [3, 1, 4, 2, 10]; nums.sort(); console.log(nums); // [1, 10, 2, 3, 4]
JavaScript
// Numeric sort using a comparator const nums2 = [3, 1, 4, 2, 10]; nums2.sort((a, b) => a - b); console.log(nums2); // [1, 2, 3, 4, 10]

Practical example: numeric sort vs string sort

Consider a dataset with mixed numbers. When sorted without a comparator, the order may reflect string rules rather than numeric magnitude. This is critical when ranking scores, ages, or identifiers.

JavaScript
const values = [7, 2, 9, 3, 5]; console.log("default:", values.slice().sort()); // default: [2,3,5,7,9] console.log("numeric:", values.slice().sort((a,b)=> a-b)); // numeric: [2,3,5,7,9]

In addition, you can chain sorts or map to secondary keys to handle complex data.

Sorting strings and locale-aware comparisons

Sorting strings often requires locale awareness, especially with accents or diacritics. Use localeCompare within a comparator to consider language rules. This keeps the sort deterministic across environments and avoids surprising results due to case or diacritics.

JavaScript
const fruits = ["banana","Apple","cherry"]; fruits.sort((a,b) => a.localeCompare(b)); console.log(fruits); // ["Apple","banana","cherry"]

For case-insensitive results, normalize cases inside the comparator:

JavaScript
const words = ["Zeta","alpha","Beta"]; words.sort((a,b) => a.toLowerCase().localeCompare(b.toLowerCase())); console.log(words); // ["alpha","Beta","Zeta"]

Steps

Estimated time: 60-90 minutes

  1. 1

    Set up a sample array

    Create an array of numbers and strings to observe default behavior vs comparator-based sorting. Start with a small, readable dataset to verify results quickly.

    Tip: Use console.log to print the array before and after sorting.
  2. 2

    Sort numbers with a numeric comparator

    Add a comparator (a,b)=>a-b to sort numerically. Test ascending and descending orders by swapping the return expression.

    Tip: Always test with edge cases like negative numbers and zeros.
  3. 3

    Sort strings with locale awareness

    Use localeCompare inside a comparator to respect language rules and accents. Compare with and without case sensitivity.

    Tip: Try sorting with accented characters to see locale impact.
  4. 4

    Sort objects by a key

    If you have an array of objects, compare based on a specific field, e.g., age or name, and extend with secondary keys.

    Tip: Provide a fallback for missing keys to avoid NaN or undefined comparisons.
  5. 5

    Handle undefined/null safely

    Filter out non-numeric values or define a clear fallback when sorting mixed data types.

    Tip: Prefer sorting a clean copy to preserve the original array.
Pro Tip: Always use a comparator for numeric sorts to avoid lexicographic results.
Warning: The sort is in-place by default. Create a copy if you need the original order later.
Note: Locale-aware sorting may vary based on environment; test on target audiences' locales.
Pro Tip: When sorting arrays of objects, extract keys to separate variables for readability.

Prerequisites

Required

Keyboard Shortcuts

ActionShortcut
Open JavaScript consoleBrowser devtoolsCtrl++J
Format code in VS CodeAuto-format on save can be configured+Alt+F
Open Command PaletteVS Code or editor with command paletteCtrl++P

Questions & Answers

What does Array.prototype.sort do by default?

The default sort converts elements to strings and sorts them lexicographically. To sort numbers correctly, you must provide a comparator function.

Default sort treats items as strings, so numbers sort like words. Provide a numeric comparator for numbers.

How do I sort numbers correctly in JavaScript?

Use a comparator such as (a,b)=>a-b to sort numbers in ascending order, or (b-a) for descending order.

Sort numbers with a numeric comparator like a-b for ascending.

Is sort stable in JavaScript?

Stability depends on the engine; most modern engines implement stable sorts, but you should not rely on it for critical logic and may need auxiliary keys.

Most engines sort stably today, but verify in your target environment.

How can I sort an array of objects by a key?

Provide a comparator that compares the object property, e.g., (a,b)=> a.age - b.age, and consider a secondary key for ties.

Sort objects by the property you care about using a comparator.

How to sort without mutating the original array?

Sort a copy of the array, e.g., [...arr].sort(...), to keep the original intact.

If you need the original order, sort a copy instead of the original.

When should I use localeCompare inside sort?

Use localeCompare when working with language-specific rules or diacritics to get correct alphabetical order.

Use localeCompare for language-aware sorting when needed.

What to Remember

  • Default sort treats elements as strings
  • Use a comparator like (a,b)=>a-b for numeric sorts
  • Locale-aware sorting relies on localeCompare
  • Sort in-place, but prefer copying when needed
  • Sort objects by primary key and optional secondary keys

Related Articles