ArticleZip > Javascript Sort Function Sort By First Then By Second

Javascript Sort Function Sort By First Then By Second

When working with arrays in JavaScript, you might find yourself needing to sort the array elements based on multiple criteria. Sorting by a primary key and then by a secondary key is a common requirement in many applications. In this article, we will explore how you can use the JavaScript sort function to achieve this two-level sorting effectively.

By default, the JavaScript sort function sorts the elements of an array alphabetically. However, when you need to sort by more than one key, you can define a custom comparison function. This function will be responsible for comparing the elements based on your specified criteria.

Let's take a look at an example. Suppose we have an array of objects representing people's information with 'age' as the primary sorting key and 'name' as the secondary sorting key:

Javascript

const people = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 25 },
  { name: 'David', age: 30 }
];

To sort this array first by 'age' and then by 'name', we can use the sort function like this:

Javascript

people.sort((a, b) => {
  if (a.age === b.age) {
    return a.name.localeCompare(b.name);
  }
  return a.age - b.age;
});

In this comparison function, we first check if the 'age' values are equal. If they are, we sort the objects by 'name' using the `localeCompare` method. If the 'age' values are not equal, we simply compare them numerically.

After calling the `sort` method with this custom comparison function, the `people` array will be sorted first by 'age' in ascending order, and then by 'name' in alphabetical order for elements with the same 'age'.

Remember that the comparison function should return a value less than 0 if the first argument should be placed before the second one, a value greater than 0 if the first argument should be placed after the second one, or 0 if the two arguments are considered equal in sorting order.

By writing custom comparison functions like the one in the example above, you can tailor the sorting behavior to meet your specific requirements, sorting the array elements by multiple criteria in the desired order. This approach gives you the flexibility to handle complex sorting scenarios with ease in your JavaScript applications.

In conclusion, the JavaScript sort function allows you to sort array elements by multiple criteria effectively. By defining a custom comparison function, you can sort the elements first by one key and then by another key, providing you with the ability to implement sophisticated sorting logic in your projects.

×