Skip to Content
Course content

46: Sorting and Comparing Arrays

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen a lot of junior developers get tripped up by how JavaScript handles arrays, specifically when they start trying to organize or compare them. On the surface, the tools are right there—.sort() and the === operator—but these tools don't always behave the way your intuition tells you they should. If you're coming from a language where == compares the contents of a list, JavaScript is going to throw you a curveball.

The "10 comes before 2" Trap

Let's say you're building a leaderboard for a game. You have an array of scores, and you want to sort them from lowest to highest. The naive move is to just call the sort method:

const scores = [10, 2, 100, 25];
scores.sort();
console.log(scores); // Expected: [2, 10, 25, 100]
// Actual: [10, 100, 2, 25]

It looks broken, right? But here's the thing: JavaScript isn't actually broken; it's just being literal. By default, .sort() converts every element into a string and then compares their UTF-16 code unit values. In a dictionary, "10" comes before "2" because it starts with a "1". It's an annoying quirk, but it's consistent.

To fix this, you have to provide a compare function. This is where you tell JavaScript exactly how to determine the order by returning a number. If the function returns a negative value, a comes first. If it's positive, b comes first. For numbers, the cleanest way to do this is a simple subtraction:

const scores = [10, 2, 100, 25];
scores.sort((a, b) => a - b); 
console.log(scores); // [2, 10, 25, 100]

I usually tell my colleagues to just memorize this pattern: (a, b) => a - b for ascending, and (a, b) => b - a for descending. It saves you from having to write a verbose if/else block every time you need to order a list of prices or IDs.

Why your arrays aren't "equal"

Now, let's talk about comparing arrays. You might be tempted to check if two arrays are the same using the strict equality operator. Imagine you're checking if a user's current selection of filters matches a saved preset:

const savedFilters = ['red', 'blue'];
const currentFilters = ['red', 'blue'];

if (savedFilters === currentFilters) {
    console.log("They match!");
} else {
    console.log("They don't match."); // This will always run
}

This happens because arrays in JavaScript are objects, and objects are compared by reference, not by value. You aren't asking "Do these two arrays have the same items?"; you're asking "Are these two variables pointing to the exact same spot in memory?" Since these are two different array literals, the answer is always no.

If you need to check if the contents are the same, you have to actually look at the elements. For small, simple arrays, I often use the .every() method. It allows you to verify that every single element in the first array matches the element at the same index in the second array. But first, you must check the length—if the lengths differ, there's no point in checking the elements.

const areArraysEqual = (arr1, arr2) => {
    if (arr1.length !== arr2.length) return false;
    return arr1.every((val, index) => val === arr2[index]);
};

console.log(areArraysEqual(['red', 'blue'], ['red', 'blue'])); // true

You might see people suggest JSON.stringify(arr1) === JSON.stringify(arr2). While that's a quick hack, it's generally a bad habit. It's computationally expensive because it converts the whole array to a string, and it will fail miserably if the order of elements is different but the content is the same. If order doesn't matter to you, your best bet is to sort both arrays first using the method we discussed above, and then run the .every() check.




📋 Practical Task

Exercise: Inventory Sync Validator

You are building a system that syncs inventory lists between a local warehouse and a central server. You need to create a function called syncInventory that takes two arrays of product IDs (numbers) and performs the following steps:

  • Sort both arrays in ascending order (lowest ID first).
  • Determine if the two sorted arrays are identical in content.
  • Return true if they match perfectly, or false if there is a discrepancy.

Test your function with these cases:

const warehouseA = [501, 102, 305, 202];
const warehouseB = [202, 501, 102, 305];
// syncInventory(warehouseA, warehouseB) should return true

const warehouseC = [501, 102, 305];
const warehouseD = [501, 102, 306];
// syncInventory(warehouseC, warehouseD) should return false
Rating
0 0

There are no comments for now.

to be the first to leave a comment.