Ship internal tools in hours, not weeks. Real auth, users, jobs, audit logs, and cohesive UI included. Early access $249 $499 → [Get it now]

How to sort an array in JavaScript

Sorting arrays is essential for organizing data, creating alphabetical lists, arranging numbers in order, and providing users with structured, easily scannable information in JavaScript applications. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented array sorting in countless components like data tables, dropdown menus, and leaderboards where proper data ordering enhances user experience. From my extensive expertise, the most modern and safe solution is the ES2023 toSorted() method, which returns a new sorted array without mutating the original. For in-place sorting, the classic sort() method remains the fastest option.

Use toSorted() to create a sorted copy of an array without mutating the original, or sort() to sort the array in place.

const fruits = ['banana', 'apple', 'orange', 'cherry']

const sorted = fruits.toSorted()

console.log(sorted)
// ['apple', 'banana', 'cherry', 'orange']

console.log(fruits)
// ['banana', 'apple', 'orange', 'cherry'] — original unchanged

The toSorted() method was introduced in ES2023 and is the preferred approach in modern JavaScript. By default, it converts elements to strings and sorts them alphabetically. It returns a new array, leaving the original untouched — which makes it safe to use in React state updates and functional pipelines where immutability matters.

Sorting numbers

The default string-based comparison does not work correctly for numbers — [10, 2, 1] would sort as [1, 10, 2]. Always pass a comparator function for numeric sorting.

const scores = [42, 7, 99, 23, 65]

const ascending = scores.toSorted((a, b) => a - b)
console.log(ascending)
// [7, 23, 42, 65, 99]

const descending = scores.toSorted((a, b) => b - a)
console.log(descending)
// [99, 65, 42, 23, 7]

The comparator function receives two elements. If it returns a negative number, a comes first. If positive, b comes first. If zero, the order stays unchanged. This convention applies to both sort() and toSorted().

Sorting an array of objects by property

When working with data from APIs, you often need to sort an array of objects by a specific property like name, date, or price.

const users = [
  { name: 'Charlie', age: 30 },
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 35 }
]

const byName = users.toSorted((a, b) => a.name.localeCompare(b.name))
console.log(byName.map(u => u.name))
// ['Alice', 'Bob', 'Charlie']

const byAge = users.toSorted((a, b) => a.age - b.age)
console.log(byAge.map(u => u.name))
// ['Alice', 'Charlie', 'Bob']

Use localeCompare() for string properties — it handles accented characters and locale-specific ordering correctly. Use numeric subtraction for number properties.

Sorting strings with localeCompare

When sorting strings that contain special characters, accents, or mixed case, localeCompare() produces the correct result where a plain comparison would fail.

const cities = ['Zürich', 'amsterdam', 'Berlin', 'éclair', 'Athens']

const sorted = cities.toSorted((a, b) =>
  a.localeCompare(b, undefined, { sensitivity: 'base' })
)

console.log(sorted)
// ['amsterdam', 'Athens', 'Berlin', 'éclair', 'Zürich']

The sensitivity: 'base' option ignores case and accent differences during comparison, so 'a' and 'A' are treated as equal. This is essential for user-facing lists where sorting must feel natural regardless of input formatting.

Using sort() for in-place sorting

The classic sort() method modifies the original array. This is more memory efficient but means the original order is lost.

const items = ['cherry', 'apple', 'banana']
items.sort()

console.log(items)
// ['apple', 'banana', 'cherry']

Only use sort() when you are certain the original array is not shared or when you explicitly want to modify it. In React components, always prefer toSorted() to avoid mutating state directly.

Sorting inside React state

When updating state, always use toSorted() so React receives a new array reference and triggers a re-render.

const [users, setUsers] = useState(initialUsers)

const sortByName = () => {
  setUsers(prev => prev.toSorted((a, b) => a.name.localeCompare(b.name)))
}

Calling sort() directly on state would mutate the existing array without creating a new reference, so React would not detect the change and would skip the re-render. This is the same pattern used in the CSmartTable component, which handles column sorting internally using immutable array operations.

Best Practice Note:

This is the same approach we use in CoreUI components for organizing dropdown options and table data. The CSmartTable component provides built-in column sorting powered by comparator functions, so you get this behavior out of the box.

In 2026, toSorted() is supported in all modern browsers and Node.js 20+. Prefer it over [...array].sort() for cleaner code. Always use a comparator for numbers, and reach for localeCompare() when sorting user-facing strings.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author