Sorting JavaScript Arrays - basic guide

Let's learn about Array.prototype.sort() in JavaScript and see why it doesn't work on numbers as expected.
Published 2023-04-23 3 min read
Sorting JavaScript Arrays - basic guide

Today, we’ll dive into the world of JavaScript arrays, focusing on the ever-so-useful and ever-so-weird Array.sort() method. Sorting is a crucial aspect of data manipulation and presentation so it’s best to learn ad understand it well.

 

JavaScript Array.sort() Method

JavaScript offers a convenient method called Array.sort() that does the heavy lifting for us. 

It can accept one argument (optional) - a compare function and returns a sorted array. Remember that sort method does the sorting in place, so it’ll affect the original array.

By default, when there is no compare function, the sort method casts elements to strings and sorts them by Unicode code point value, which might produce unexpected results when sorting numbers, objects or even localized strings. Let’s look at a number example:

const numberArray = [20, 10, 5, 100];
numberArray.sort();
console.log(numberArray); // Output: [10, 100, 20, 5]

Don’t worry; we’ll address this issue in the next section!

 

Customizing Array.sort() with Compare Functions

To get the desired sorting behavior, we can pass a custom compare function to Array.sort(). The compare function should return a negative, zero, or positive value, depending on the sort order. Negative result will swap items order.

Let’s sort our previous example in ascending order:

const numberArray = [20, 10, 5, 100];
numberArray.sort((a, b) => a - b);
console.log(numberArray); // Output: [5, 10, 20, 100]

To sort the array in descending order, we simply reverse the subtraction:

numberArray.sort((a, b) => b - a);
console.log(numberArray); // Output: [100, 20, 10, 5]

If you’re dealing with an array of objects, you can easily sort them based on a specific property:

const fruitArray = [
  { name: 'apple', quantity: 5 },
  { name: 'banana', quantity: 10 },
  { name: 'orange', quantity: 3 }
];

// Sort by quantity (ascending)
fruitArray.sort((a, b) => a.quantity - b.quantity);
console.log(fruitArray);

 

Common Pitfalls and Best Practices

Using Array.sort() may seem straightforward, but there are a few common pitfalls to avoid:

  • Remember that Array.sort() sorts elements as strings by default. Use a custom compare function for numbers or other data types.
  • Array.sort() modifies the original array. If you need to preserve the original order, create a copy before sorting (e.g., using Array.slice() or by spread operator).

 

And here are some best practices to keep in mind:

  • Use arrow functions for concise and readable compare functions.
  • Always provide a compare function for complex data types (e.g., objects) to ensure the desired sorting behavior.

 

Sorting by multiple parameters in an object

Sometimes, you may need to sort an array based on multiple criteria. In such cases, you can chain sorting methods:

const movieArray = [
  { title: 'The Matrix', year: 1999, rating: 8.8 },
  { title: 'The Matrix Reloaded', year: 2003, rating: 7.2 },
  { title: 'Interstellar', year: 2014, rating: 8.6 },
  { title: 'Inception', year: 2010, rating: 8.8 },
];

// Sort by rating (descending), then by year (ascending)
movieArray.sort((a, b) => {
  if (b.rating - a.rating !== 0) {
    return b.rating - a.rating;
  }

  return a.year - b.year;
});

console.log(movieArray);

Note we’ve leveraged the fact that compare function can be anything as long as it returns a Number. To be honest it can return anything - the result will be casted to Number. There are some other requirements for a good compare function - it should be stable etc., but in reality, anything goes, as it’s the case for most of the JS code. Hope this helps you to get familiarized yourself with sorting in JavaScript. 

#javascript