top of page

JavaScript for Kids: Array Sort

Hey there, future coders! Today we're going to learn about something super cool: sorting arrays. Don't worry if that sounds complicated - it's just a fancy way of saying "putting lists in order." Let's dive in!


What Are Arrays?


We learned in the previous lesson that arrays are like a magical box that can hold lots of different things.


Why Do We Need to Sort?

Sometimes, our arrays (or lists) get messy. Maybe we have a list of numbers all jumbled up, or a list of names that isn't in alphabetical order. Sorting helps us organize these lists so we can find things easily.


JavaScript's Built-in Sorting

JavaScript has a super cool built-in method to sort arrays. It's called sort(). Let's try it out!


let numbers = [5, 2, 8, 1, 9];
numbers.sort();
console.log(numbers);  // Output: [1, 2, 5, 8, 9]

Wow! JavaScript sorted our numbers for us. But wait, there's a catch...


The Tricky Part

JavaScript's sort() method has a secret: it sorts things as if they were text, even when they're numbers! This can lead to some funny results:


let bigNumbers = [1, 5, 10, 2, 20];
bigNumbers.sort();
console.log(bigNumbers);  // Output: [1, 10, 2, 20, 5]

Oops! That's not quite right. So how do we fix it?


Sorting Numbers the Right Way

To sort numbers correctly, we need to give sort() some extra instructions. Don't worry, it's not as hard as it sounds!


let bigNumbers = [1, 5, 10, 2, 20];
bigNumbers.sort(function(a, b) {
    return a - b;
});
console.log(bigNumbers);  // Output: [1, 2, 5, 10, 20]

Sorting Words

Sorting words (or strings) is easier because that's what sort() likes to do naturally:


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

Fun Challenge: Sorting in Reverse


Want to sort your array backwards? Just add reverse() after sort()!

let numbers = [1, 5, 2, 8, 3];
numbers.sort(function(a, b) {
    return a - b;
}).reverse();
console.log(numbers);  // Output: [8, 5, 3, 2, 1]

Let's Practice!

Try sorting these arrays:

  1. [42, 8, 16, 4, 23]

  2. ["zebra", "elephant", "giraffe", "lion"]


Wrapping Up


Great job, young coders! You've learned how to sort arrays in JavaScript.


Remember:

  • Use sort() for words

  • Use sort(function(a, b) { return a - b; }) for numbers

  • Add reverse() to sort backwards


Keep practicing, and soon you'll be a JavaScript sorting master!

Happy coding, kids!

Comments


Subscribe to WeCode newsletter

Receive News and Updates

Thanks for submitting!

  • Twitter
  • Facebook
  • Linkedin

© 2024 by WeCode. Proudly created with Wix.com

bottom of page