JavaScript Tutorial

JavaScript Array Sort

JavaScript में sort() method का उपयोग array को sort (क्रमबद्ध) करने के लिए किया जाता है।
यह method original array को बदल देता है और इसे alphabetically या custom logic से ascending/descending क्रम में sort किया जा सकता है।

इस अध्याय में आप सीखेंगे:


🔹 1. Default sort() – Alphabetical (Strings)

जब आप सीधे sort() use करते हैं, तो यह array के items को strings के रूप में alphabetically sort करता है।

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

❗ यह सभी values को string में convert करके compare करता है, इसलिए numbers के लिए गलत result दे सकता है।


🔹 2. Default sort() on Numbers – ⚠️ Unexpected Results

let numbers = [40, 100, 1, 5, 25, 10];
numbers.sort();
console.log(numbers);  // Output: [1, 10, 100, 25, 40, 5] ❌

क्योंकि यह numbers को भी string की तरह sort करता है:


🔹 3. Custom Sort for Numbers – ✅ सही तरीका

Ascending Order (छोटे से बड़े)

let numbers = [40, 100, 1, 5, 25, 10];
numbers.sort((a, b) => a - b);
console.log(numbers);  // Output: [1, 5, 10, 25, 40, 100]

Descending Order (बड़े से छोटे)

numbers.sort((a, b) => b - a);
console.log(numbers);  // Output: [100, 40, 25, 10, 5, 1]

🔹 4. Sorting Strings (Case Sensitivity)

let names = ["rahul", "Amit", "neha", "Geeta"];
names.sort();
console.log(names);  // Output: ["Amit", "Geeta", "neha", "rahul"]

पहले capital letters (A-Z) और फिर small letters (a-z) आते हैं।


🔹 5. Sort + Reverse

let colors = ["red", "blue", "green"];
colors.sort();       // ["blue", "green", "red"]
colors.reverse();    // ["red", "green", "blue"]

🔹 6. Sort Array of Objects (By Property)

आप किसी object array को भी sort कर सकते हैं।

let students = [
  { name: "Ravi", marks: 85 },
  { name: "Anu", marks: 92 },
  { name: "Kiran", marks: 78 }
];

students.sort((a, b) => b.marks - a.marks);

console.log(students);
// Output:
// [
//   { name: "Anu", marks: 92 },
//   { name: "Ravi", marks: 85 },
//   { name: "Kiran", marks: 78 }
// ]

📋 Summary Table

Use CaseSyntaxResult Type
Strings alphabeticallyarr.sort()Sorted array
Numbers ascendingarr.sort((a, b) => a - b)Sorted array
Numbers descendingarr.sort((a, b) => b - a)Sorted array
Objects by propertyarr.sort((a, b) => a.key - b.key)Sorted array
Reverse arrayarr.reverse()Reversed array

अभ्यास प्रश्न

  1. sort() method का default behavior क्या है और यह numbers के साथ गलत result क्यों दे सकता है?
  2. नीचे दिए गए code का output क्या होगा? let arr = [15, 3, 22, 7]; arr.sort(); console.log(arr);
  3. एक ऐसा sort function लिखिए जो numbers को descending order में sort करे।
  4. "Delhi", "agra", "Mumbai", "kolkata" को सही तरीके से alphabetically sort कीजिए (case-insensitive)।
  5. एक object array बनाइए जिसमें students का नाम और age हो, और उसे सबसे छोटे age वाले से sort कीजिए।