โ† Back Creator Path ๐Ÿ’Ž Crystal Cavern Lesson 78/20
๐ŸŽฏ Missions
1 Collect crystals
2 Sort by size
3 Display collection!
๐Ÿ’Ž โœจ ๐Ÿ”ฎ
๐Ÿ’Ž Crystal Cavern
Crystal Cavern
Deep in the Crystal Cavern, gems are scattered everywhere! But before you can display your collection, you need to SORT them. Meet .sort() โ€” the magic that puts your crystals in order!

๐Ÿ’Ž What is .sort()?

Imagine you have a pile of gems. You could arrange them ONE BY ONE... or use .sort() to put them in order automatically!

.sort() takes every item in an array and rearranges them based on their values. It's perfect for:

// Sort numbers from smallest to biggest
const sizes = [50, 10, 30, 20];

const sorted = sizes.sort((a, b) => a - b);
// Result: [10, 20, 30, 50]

How it works:

โ€ข (a, b) => a - b means "smallest first"
โ€ข (a, b) => b - a means "biggest first"
โ€ข The function compares pairs and swaps them until everything is in order!

// The sorting formula:
array.sort((a, b) => a - b) // ascending (1, 2, 3)
array.sort(=> b - a) // descending (3, 2, 1)
โœ๏ธ CODE
// ๐Ÿ’Ž Crystal Cavern - Sort your gems! const crystals = [85, 12, 47, 30]; // Sort from smallest to biggest: const sorted = crystals.sort((a, b) => a - b); console.log("Sorted: " + sorted);
โœจ RESULT
๐Ÿ’ŽFound: 0
โœจSorted: 0
Your Crystal Collection
Mine crystals below!

โ›๏ธ Mine Crystals

๐Ÿ”„ Sort By

Your Sorted Collection
โ€”

1 Challenge: Sort Words

Can you sort an array of words in alphabetical order? The default .sort() without a function works for strings!

const gems = ["Ruby", "Emerald", "Sapphire"]; const sorted = gems.sort(); // Result: ["Emerald", "Ruby", "Sapphire"]

2 Challenge: Descending Order

Sort from BIGGEST to smallest using (a, b) => b - a

const scores = [95, 82, 88]; const ranked = scores.sort((a, b) => b - a); // Result: [95, 88, 82]

3 Challenge: Combine with Reduce

Sort first, then use .reduce() to find the TOTAL! Sort these numbers, then add them all up.

const prices = [30, 10, 50, 20];
const sorted = prices.sort((a, b) => a - b);
const total = sorted.reduce((sum, n) => sum + n, 0);
// Sorted: [10, 20, 30, 50], Total: 110

4 Challenge: Find the Middle

Sort the array, then find the middle value using index Math.floor(arr.length / 2)

const ages = [14, 8, 11]; const sorted = ages.sort((a, b) => a - b); const middle = sorted[Math.floor(sorted.length / 2)]; // Result: 11

5 Challenge: Median Finder

Create a function that finds the median value of ANY sorted array!

function findMedian(arr) {
  const sorted = arr.sort((a, b) => a - b);
  const mid = Math.floor(sorted.length / 2);
  return sorted[mid];
}
findMedian([5, 2, 8, 1]);
// Result: 5

โœจ What You Learned