JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Sorting Arrays

8 April 2025 | Category:

JavaScript allows you to sort arrays using the built-in sort() method.

You can sort strings, numbers, and even use custom sorting logic using compare functions.


✅ 1. sort() – Sort Alphabetically (Strings)

The sort() method sorts the array in place, converting elements to strings by default.

let fruits = ["Banana", "Apple", "Orange"];
fruits.sort();

console.log(fruits); // ["Apple", "Banana", "Orange"]

⚠️ Warning with Numbers

let numbers = [100, 20, 3];
numbers.sort();

console.log(numbers); // [100, 20, 3] => Actually becomes ["100", "20", "3"]

sort() converts numbers to strings by default, which can cause incorrect results.


✅ 2. Sorting Numbers Correctly

To sort numbers properly, use a compare function:

🔼 Ascending Order:

let numbers = [100, 20, 3];
numbers.sort((a, b) => a - b);

console.log(numbers); // [3, 20, 100]

🔽 Descending Order:

numbers.sort((a, b) => b - a);
console.log(numbers); // [100, 20, 3]

✅ 3. reverse() – Reverse the Order

You can also reverse the order of elements in an array.

let colors = ["Red", "Green", "Blue"];
colors.reverse();

console.log(colors); // ["Blue", "Green", "Red"]

💡 Use .sort().reverse() to sort in descending order for strings.


✅ 4. Sort an Array of Objects

You can also sort objects based on properties.

📅 Sort by Numeric Property:

let products = [
  { name: "Pen", price: 20 },
  { name: "Pencil", price: 10 },
  { name: "Notebook", price: 50 }
];

products.sort((a, b) => a.price - b.price);
console.log(products);
// Sorted by price: Pencil, Pen, Notebook

🔤 Sort by String Property:

products.sort((a, b) => a.name.localeCompare(b.name));
console.log(products);
// Sorted alphabetically by name

📌 Summary Table

MethodDescription
sort()Sorts array (as strings by default)
reverse()Reverses array order
compareFunctionAllows custom sorting logic
localeCompare()Sort strings with correct locale rules

🧠 Final Tips

  • Use a compare function when sorting numbers or objects.
  • Combine sort() and reverse() for simple descending sorts.
  • Use localeCompare() for accurate string sorting in other languages.