JavaScript Array Sort

Organize and arrange array elements in order

🔄 What is Array Sorting?

Array sorting arranges elements in a specific order - alphabetically, numerically, or by custom rules. JavaScript provides powerful methods to sort arrays easily.


let fruits = ["banana", "apple", "cherry"];
fruits.sort();
console.log(fruits); // ["apple", "banana", "cherry"]
                                    

Output:

["apple", "banana", "cherry"]

Types of Sorting

🔤

Alphabetical

Sort strings in alphabetical order

arr.sort()
🔢

Numerical

Sort numbers in ascending/descending order

arr.sort((a, b) => a - b)
🔄

Reverse

Sort in reverse order

arr.reverse()
⚙️

Custom

Sort by custom rules and conditions

arr.sort(compareFunction)

🔹 Basic String Sorting

The simplest way to sort arrays of strings:

// Basic alphabetical sorting
let animals = ["zebra", "cat", "dog", "elephant", "ant"];
animals.sort();
console.log(animals); // ["ant", "cat", "dog", "elephant", "zebra"]

// Case matters in sorting
let names = ["john", "Alice", "bob", "Charlie"];
names.sort();
console.log(names); // ["Alice", "Charlie", "bob", "john"]

// Case-insensitive sorting
let cities = ["paris", "London", "tokyo", "New York"];
cities.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
console.log(cities); // ["London", "New York", "paris", "tokyo"]

// Reverse alphabetical order
let fruits = ["apple", "banana", "cherry"];
fruits.sort().reverse();
console.log(fruits); // ["cherry", "banana", "apple"]

// Or sort in reverse directly
let colors = ["red", "blue", "green"];
colors.sort((a, b) => b.localeCompare(a));
console.log(colors); // ["red", "green", "blue"]

Output:

["ant", "cat", "dog", "elephant", "zebra"]
["Alice", "Charlie", "bob", "john"]
["London", "New York", "paris", "tokyo"]
["cherry", "banana", "apple"]
["red", "green", "blue"]

🔹 Numerical Sorting

Sorting numbers requires special handling:

// Wrong way - treats numbers as strings
let numbers1 = [10, 5, 40, 25, 1000, 1];
numbers1.sort();
console.log(numbers1); // [1, 10, 1000, 25, 40, 5] - Wrong!

// Correct way - ascending order
let numbers2 = [10, 5, 40, 25, 1000, 1];
numbers2.sort((a, b) => a - b);
console.log(numbers2); // [1, 5, 10, 25, 40, 1000] - Correct!

// Descending order
let numbers3 = [10, 5, 40, 25, 1000, 1];
numbers3.sort((a, b) => b - a);
console.log(numbers3); // [1000, 40, 25, 10, 5, 1]

// Sorting decimal numbers
let prices = [19.99, 5.50, 100.00, 0.99, 50.25];
prices.sort((a, b) => a - b);
console.log(prices); // [0.99, 5.5, 19.99, 50.25, 100]

// Sorting negative numbers
let temperatures = [-5, 10, -15, 0, 25, -3];
temperatures.sort((a, b) => a - b);
console.log(temperatures); // [-15, -5, -3, 0, 10, 25]

Output:

[1, 10, 1000, 25, 40, 5]
[1, 5, 10, 25, 40, 1000]
[1000, 40, 25, 10, 5, 1]
[0.99, 5.5, 19.99, 50.25, 100]
[-15, -5, -3, 0, 10, 25]

🔹 Sorting Objects

Sort arrays of objects by their properties:

let students = [
    {name: "Alice", age: 23, grade: 85},
    {name: "Bob", age: 20, grade: 92},
    {name: "Charlie", age: 25, grade: 78},
    {name: "Diana", age: 22, grade: 96}
];

// Sort by name (alphabetically)
let byName = [...students].sort((a, b) => a.name.localeCompare(b.name));
console.log(byName.map(s => s.name)); // ["Alice", "Bob", "Charlie", "Diana"]

// Sort by age (ascending)
let byAge = [...students].sort((a, b) => a.age - b.age);
console.log(byAge.map(s => `${s.name}: ${s.age}`)); 
// ["Bob: 20", "Diana: 22", "Alice: 23", "Charlie: 25"]

// Sort by grade (descending - highest first)
let byGrade = [...students].sort((a, b) => b.grade - a.grade);
console.log(byGrade.map(s => `${s.name}: ${s.grade}`)); 
// ["Diana: 96", "Bob: 92", "Alice: 85", "Charlie: 78"]

// Products example
let products = [
    {name: "Laptop", price: 999, category: "Electronics"},
    {name: "Book", price: 15, category: "Education"},
    {name: "Phone", price: 699, category: "Electronics"}
];

// Sort by price (low to high)
products.sort((a, b) => a.price - b.price);
console.log(products.map(p => `${p.name}: $${p.price}`));
// ["Book: $15", "Phone: $699", "Laptop: $999"]

Output:

["Alice", "Bob", "Charlie", "Diana"]
["Bob: 20", "Diana: 22", "Alice: 23", "Charlie: 25"]
["Diana: 96", "Bob: 92", "Alice: 85", "Charlie: 78"]
["Book: $15", "Phone: $699", "Laptop: $999"]

🔹 Advanced Sorting Techniques

Complex sorting scenarios and custom logic:

// Multi-level sorting (sort by category, then by price)
let items = [
    {name: "Laptop", price: 999, category: "Electronics"},
    {name: "Book", price: 15, category: "Education"},
    {name: "Phone", price: 699, category: "Electronics"},
    {name: "Notebook", price: 5, category: "Education"}
];

items.sort((a, b) => {
    // First sort by category
    if (a.category !== b.category) {
        return a.category.localeCompare(b.category);
    }
    // Then sort by price within same category
    return a.price - b.price;
});
console.log(items.map(i => `${i.category}: ${i.name} ($${i.price})`));

// Sort by string length
let words = ["JavaScript", "HTML", "CSS", "React", "Vue"];
words.sort((a, b) => a.length - b.length);
console.log(words); // ["CSS", "Vue", "HTML", "React", "JavaScript"]

// Sort dates
let dates = [
    new Date('2023-12-25'),
    new Date('2023-01-01'),
    new Date('2023-07-04'),
    new Date('2023-03-15')
];
dates.sort((a, b) => a - b); // Oldest first
console.log(dates.map(d => d.toDateString()));

// Custom priority sorting
let tasks = [
    {task: "Buy groceries", priority: "medium"},
    {task: "Finish project", priority: "high"},
    {task: "Call mom", priority: "low"},
    {task: "Pay bills", priority: "high"}
];

const priorityOrder = {high: 3, medium: 2, low: 1};
tasks.sort((a, b) => priorityOrder[b.priority] - priorityOrder[a.priority]);
console.log(tasks.map(t => `${t.priority}: ${t.task}`));

Output:

["Education: Notebook ($5)", "Education: Book ($15)", "Electronics: Phone ($699)", "Electronics: Laptop ($999)"]
["CSS", "Vue", "HTML", "React", "JavaScript"]
["Sun Jan 01 2023", "Wed Mar 15 2023", "Tue Jul 04 2023", "Mon Dec 25 2023"]
["high: Finish project", "high: Pay bills", "medium: Buy groceries", "low: Call mom"]

🔹 Practical Sorting Examples

Real-world applications of array sorting:

// E-commerce product sorting
let products = [
    {name: "Wireless Mouse", price: 25, rating: 4.5, reviews: 120},
    {name: "Keyboard", price: 75, rating: 4.8, reviews: 89},
    {name: "Monitor", price: 200, rating: 4.2, reviews: 45},
    {name: "Webcam", price: 50, rating: 4.0, reviews: 200}
];

// Sort by popularity (most reviews first)
function sortByPopularity(products) {
    return [...products].sort((a, b) => b.reviews - a.reviews);
}

// Sort by best rating
function sortByRating(products) {
    return [...products].sort((a, b) => b.rating - a.rating);
}

// Sort by price (low to high)
function sortByPrice(products) {
    return [...products].sort((a, b) => a.price - b.price);
}

console.log("Most Popular:", sortByPopularity(products)[0].name);
console.log("Highest Rated:", sortByRating(products)[0].name);
console.log("Cheapest:", sortByPrice(products)[0].name);

// Leaderboard sorting
let players = [
    {name: "Alice", score: 1250, level: 15},
    {name: "Bob", score: 980, level: 12},
    {name: "Charlie", score: 1250, level: 18},
    {name: "Diana", score: 1100, level: 14}
];

// Sort by score (high to low), then by level if scores are equal
players.sort((a, b) => {
    if (a.score !== b.score) {
        return b.score - a.score; // Higher score first
    }
    return b.level - a.level; // Higher level first if scores equal
});

console.log("Leaderboard:");
players.forEach((player, index) => {
    console.log(`${index + 1}. ${player.name} - Score: ${player.score}, Level: ${player.level}`);
});

Output:

Most Popular: Webcam
Highest Rated: Keyboard
Cheapest: Wireless Mouse
Leaderboard:
1. Charlie - Score: 1250, Level: 18
2. Alice - Score: 1250, Level: 15
3. Diana - Score: 1100, Level: 14
4. Bob - Score: 980, Level: 12

🧠 Test Your Knowledge

How do you sort numbers in ascending order?