DEV Community

Cover image for Understanding Array.prototype.sort() in JavaScript: A Beginner's Guide
Diego Palacios Lepore
Diego Palacios Lepore

Posted on

Understanding Array.prototype.sort() in JavaScript: A Beginner's Guide

Introduction

Have you ever stumbled upon the Array.prototype.sort() method and found yourself scratching your head?

scratching head

You're not alone! It's an incredibly useful tool, but it can be somewhat confusing. So, grab a coffee, and let's see how sort() operates, using some practical examples to clarify things.

Basic Sorting: An Unexpected Twist

Starting with the fundamentals, the sort() method, by default, arranges array elements as strings in ascending sequence:

const nums = [40, 1, 5, 200];
nums.sort();
console.log(nums); // Output: [1, 200, 40, 5]
Enter fullscreen mode Exit fullscreen mode

Surprised? It's because sort() converts numbers into strings for comparison, making '200' smaller than '40'.

Tailored Sorting with a Compare Function

Need more precision? You can employ a compare function with sort():

nums.sort((a, b) => a - b);
console.log(nums); // Output: [1, 5, 40, 200]
Enter fullscreen mode Exit fullscreen mode

Here's the secret formula:

  • Below 0: a comes before b.
  • 0: a and b remain unchanged.
  • Above 0: b comes before a.

Want the reverse order? Simply reverse the equation:

nums.sort((a, b) => b - a);
console.log(nums); // Output: [200, 40, 5, 1]
Enter fullscreen mode Exit fullscreen mode

String Sorting

Need to sort strings? Think about case insensitivity:

const fruits = [ 'Kiwi', 'Banana', 'banana', 'Cherry', 'apple', ];
fruits.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
console.log(fruits); // Output: [ 'apple', 'banana', 'Banana', 'Cherry', 'Kiwi' ]
Enter fullscreen mode Exit fullscreen mode

But why does this also work?

const fruits = [ 'Kiwi', 'Banana', 'banana', 'Cherry', 'apple', ];
fruits.sort((a, b) => a.localeCompare(b));
console.log(fruits); // Output: [ 'apple', 'banana', 'Banana', 'Cherry', 'Kiwi' ]
Enter fullscreen mode Exit fullscreen mode

It's due to the String.prototype.localeCompare method, which adjusts to the locale and environment.

Object Sorting: Managing Your Digital Shop

Have a product array?

const merchandise = [
  { name: 'Laptop', price: 1000 },
  { name: 'Mouse', price: 20 },
  { name: 'Keyboard', price: 50 }
];
Enter fullscreen mode Exit fullscreen mode

Sort by cost effortlessly:

merchandise.sort((a, b) => a.price - b.price);
console.log(merchandise);
// Output: [{ name: 'Mouse', price: 20 }, { name: 'Keyboard', price: 50 }, { name: 'Laptop', price: 1000 }]
Enter fullscreen mode Exit fullscreen mode

Advice and Warnings: The Small Details

  1. On-the-spot Sorting: sort() modifies the original array. No duplicates here!
  2. Consistency: Sometimes the sequence remains, sometimes not. It's unpredictable!
  3. Undefined Values: They always land at the tail end.

Conclusion: Sort Like an Expert

The Array.prototype.sort() method is akin to a multi-tool for array sorting in JavaScript. Yes, it has its oddities, particularly with numbers, but with a tailored compare function, you have the reins. Now that you've mastered it, you'll see it as an essential part of your developer toolkit. Enjoy sorting! 🚀

Top comments (0)