🧠 Sorting Arrays in JavaScript

🧠 Sorting Arrays in JavaScript

“An array is either under control… or it will embarrass you in production.” 😅

Sorting arrays in JavaScript looks like a one-liner, but behind the scenes, tiny devils are at work.
In this article, we’ll cover:

✔️ Why arrays get sorted incorrectly
✔️ What sort() really does
✔️ Numbers, strings, objects, Turkish characters
✔️ Safe and professional usage
✔️ Practical real-world tips

All explained with lots of examples and lots of humor.


📦 1. The sort() Method: Quiet but Dangerous

The main method used to sort arrays in JavaScript is:

array.sort()

But…
This method looks innocent, yet it secretly causes chaos 😄


🔍 First Try (The Innocent Mistake)

let numbers = [1, 10, 2, 5];
numbers.sort();
console.log(numbers);

📤 Output:

[1, 10, 2, 5]

🤨 “Is this… sorted?”


🧠 What’s Actually Happening?

By default, sort():

👉 Converts elements to strings
👉 Sorts them alphabetically (dictionary order)

So JavaScript is actually thinking like this:

["1", "10", "2", "5"]

📌 Rule:
sort() is not a mathematician — it’s a literature major 😄


🔢 2. Sorting Numbers Properly (Compare Function)

This is the heart of the matter 💓
If you pass a compare function to sort(), you take control.


✅ Ascending Order (Small to Large)

let numbers = [1, 10, 2, 5];

numbers.sort((a, b) => a - b);
console.log(numbers);

📤 Output:

[1, 2, 5, 10]


🧠 What Does This Function Do?

  • a - b < 0a comes first
  • a - b > 0b comes first
  • 0 → no change

🎯 Example:

(2, 10) => 2 - 10 = -8 → 2 comes first


🔽 Descending Order (Large to Small)

numbers.sort((a, b) => b - a);

📤 Output:

[10, 5, 2, 1]

📌 Memory Tip:

  • Ascending → a - b
  • Descending → b - a

🔤 3. String Arrays: Looks Fine… Until It’s Not

let names = ["Zeynep", "Ahmet", "Mehmet", "Can"];
names.sort();
console.log(names);

📤 Output:

["Ahmet", "Can", "Mehmet", "Zeynep"]

So far, so good 👍
But now let’s add Turkish characters.


🇹🇷 4. Turkish Characters & localeCompare (The Lifesaver)

let cities = ["İzmir", "Ankara", "Çanakkale", "Bursa"];
cities.sort();
console.log(cities);

😬 This will most likely be sorted incorrectly.


✅ The Correct & Professional Way

cities.sort((a, b) => a.localeCompare(b, "tr"));
console.log(cities);

📤 Output:

["Ankara", "Bursa", "Çanakkale", "İzmir"]


🧠 Why Does This Work?

  • localeCompare knows language rules
  • "tr" → sorts according to the Turkish alphabet

📌 Real-World Tip:
E-commerce, listings, admin panels → always use localeCompare


🧍‍♂️ 5. Arrays of Objects (This Is Where Real Life Begins)

let users = [
  { name: "Ayşe", age: 25 },
  { name: "Mehmet", age: 30 },
  { name: "Can", age: 20 }
];


🎂 Sorting by Age

users.sort((a, b) => a.age - b.age);

📤 Output:

[
  { name: "Can", age: 20 },
  { name: "Ayşe", age: 25 },
  { name: "Mehmet", age: 30 }
]

📌 Logic:
JavaScript can compare not just numbers, but numbers inside objects.


🔤 Sorting by Name (Turkish-Friendly)

users.sort((a, b) => a.name.localeCompare(b.name, "tr"));

💡 Same rule applies to strings.


⚠️ 6. The Most Dangerous Trap: sort() Mutates the Original Array!

let arr = [3, 1, 2];
let sortedArr = arr.sort();

😱 WARNING:
arr is now [1, 2, 3]


🛡️ Safe & Professional Usage

let sortedArr = [...arr].sort((a, b) => a - b);

📌 Why Is This Important?

  • React state
  • Redux
  • Vue data
  • Production bugs 😅

“If you sort without copying the array, you are brave… but you are not alone.”


🚀 7. Advanced: Sorting by Multiple Criteria

let people = [
  { name: "Ali", age: 30 },
  { name: "Ali", age: 20 },
  { name: "Veli", age: 25 }
];

First by name, then by age

people.sort((a, b) => {
  if (a.name === b.name) {
    return a.age - b.age;
  }
  return a.name.localeCompare(b.name, "tr");
});

📌 This level is commonly asked in interviews 😉


🧠 8. Mini Cheat Sheet (Save This 📌)

sort() alone → risky
✅ Numbers → (a, b) => a - b
🔽 Descending → (a, b) => b - a
🇹🇷 Turkish → localeCompare("tr")
🧍‍♂️ Objects → compare via properties
🛡️ Preserve original → [...array]


🎯 Final Words

Sorting arrays in JavaScript:

“It starts simple, gets deep, and becomes fun once you master it.” 😄

Comments

No comments yet. Why don’t you start the discussion?

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir