-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
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.
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.
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 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.
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
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 5, 40, 100]
numbers.sort((a, b) => b - a);
console.log(numbers); // [100, 40, 5, 1]
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"]
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"]
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);
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]
let students = ["Olivia", "Emma", "Sophia", "Lily"];
students.sort();
console.log(students); // ["Emma", "Lily", "Olivia", "Sophia"]
let scores = [45, 78, 90, 60];
scores.sort((a, b) => a - b); // ascending
console.log(scores); // [45, 60, 78, 90]
scores.sort((a, b) => b - a);
console.log(scores); // [90, 78, 60, 45]
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);
let names = ["emma", "Lily", "Sophia", "olivia"];
names.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
console.log(names); // ["emma", "Lily", "olivia", "Sophia"]
let numbers = [10, 5, 40, 100];
numbers.sort((a, b) => a - b).reverse();
console.log(numbers); // [100, 40, 10, 5]
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.
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.
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.
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()?
Write and run code directly in your browser. Live preview for frontend languages.
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
