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 versatile and built-in solution is using the sort() method, which can handle both simple and complex sorting scenarios. This method is powerful, customizable, and works efficiently for most sorting requirements.

Use the sort() method to arrange array elements in ascending or descending order.

const fruits = ['banana', 'apple', 'orange']
fruits.sort()
// Result: ['apple', 'banana', 'orange']

The sort() method arranges the elements of an array in place and returns the sorted array. By default, it converts elements to strings and sorts them alphabetically. In this example, fruits.sort() arranges the fruit names alphabetically: ['apple', 'banana', 'orange']. For numbers, use a comparison function: numbers.sort((a, b) => a - b) for ascending order or numbers.sort((a, b) => b - a) for descending order. The method modifies the original array.

Best Practice Note:

This is the same approach we use in CoreUI components for organizing dropdown options and table data throughout our component library. For complex objects, use custom comparisons: users.sort((a, b) => a.name.localeCompare(b.name)). To avoid mutating the original array, create a copy first: [...array].sort(). Use localeCompare() for proper string sorting with special characters and locales.


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