SoFunction
Updated on 2025-04-10

Detailed explanation of how to use JavaScript sort sort

Preface

In JavaScript,sortMethods are an important part of array objects. It provides a simple and powerful way to sort arrays. This article will introduce in detailsortThe basic concepts, usage, common application scenarios, comparisons with other sorting methods, and provide practical examples to help you fully master this powerful tool.

1. Basic concepts of sort method

sortMethods are used to sort array elements and return the sorted array. By default,sortThe method is sorted by string Unicode code points. This means that if the array elements are numbers, they will be sorted in character order, not numeric order. Therefore, when sorting arrays of numbers, it is often necessary to provide a comparison function.

grammar:

([compareFunction])

compareFunction (optional): Function used to define the sort order. If this parameter is omitted, the array elements will be sorted by string Unicode code points.

2. Basic usage examples

Here is a simple example, usingsortMethods sort string arrays:

const fruits = ['banana', 'apple', 'cherry'];
();
(fruits);

// Output: ['apple', 'banana', 'cherry']

In this example,sortMethods are alphabeticalfruitsArrays for sorting.

3. Numerical sorting

Since the default sorting method sorts numbers in character order, a comparison function needs to be provided when sorting a numeric array. The comparison function takes two parameters and returns a numeric value:

  • If the return value is less than 0,aWill be rankedbBefore.
  • If the return value is equal to 0,aandbThe relative order remains the same.
  • If the return value is greater than 0,aWill be rankedbafter.

Example: Ascending order sort

const numbers = [10, 5, 20, 3];
((a, b) => a - b);
(numbers); 

// Output: [3, 5, 10, 20]

In this example, the comparison function isa - bmake surenumbersArrays are sorted in ascending order.

Example: Sort in descending order

((a, b) => b - a);
(numbers);

// Output: [20, 10, 5, 3]

In this example, the comparison function isb - amake surenumbersArrays are sorted in descending order.

4. Ordering of object arrays

In actual development, it is often necessary to sort object arrays. The array can be sorted based on a certain property of the object by providing a comparison function.

Example: Sort by object properties

const users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 20 }
];
((a, b) =>  - );
(users);

// Output:
// [
//   { name: 'Charlie', age: 20 },
//   { name: 'Alice', age: 25 },
//   { name: 'Bob', age: 30 }
// ]

In this example, the comparison function is - make sureusersArray pressageAttributes sort in ascending order.

5. Handle special circumstances

Handle case-insensitive sorting

The default string sort is case sensitive. If you need to do case-insensitive sorting, you can use it in the comparison functiontoLowerCasemethod.

const fruits = ['banana', 'Apple', 'cherry'];
((a, b) => ().localeCompare(()));
(fruits); 

// Output: ['Apple', 'banana', 'cherry']

Processing containsundefinedArray of

In order, containsundefinedWhen an array ofundefinedTreat as the maximum or minimum value, place it at the end or beginning of the array by comparing functions.

const arr = [3, undefined, 1, 2];
((a, b) => {
  if (a === undefined) return 1;
  if (b === undefined) return -1;
  return a - b;
});
(arr); 

// Output: [1, 2, 3, undefined]

6. Comparison with other sorting methods

sortCompared with other sorting methods (such as manually implemented sorting algorithms), the method has the advantages of simplicity and efficiency. Although manually implementing sorting algorithms (such as bubble sorting, quick sorting) can better understand the sorting principle, in actual development, the built-insortThe method is usually easier and more efficient.

Bubble sorting example

function bubbleSort(arr) {
  for (let i = 0; i < ; i++) {
    for (let j = 0; j <  - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
      }
    }
  }
  return arr;
}
const numbers = [5, 3, 8, 4, 2];
(bubbleSort(numbers)); 

// Output: [2, 3, 4, 5, 8]

Although this manually implemented bubble sort can complete the sorting task, it is related to the built-insortCompared with the method, it has more code volume and less efficient code.

7. Practical examples

Example 1: Sort students' names alphabetically

Suppose we have an array containing student names that need to be sorted alphabetically:

const students = ['John', 'Anna', 'Zara', 'Bob'];
();
(students); 

// Output: ['Anna', 'Bob', 'John', 'Zara']

Example 2: Sort student object array by score

Suppose we have an array containing student objects that need to be sorted by scores:

const students = [
  { name: 'John', score: 85 },
  { name: 'Anna', score: 92 },
  { name: 'Zara', score: 74 },
  { name: 'Bob', score: 89 }
];
((a, b) =>  - );
(students);

// Output:
// [
//   { name: 'Anna', score: 92 },
//   { name: 'Bob', score: 89 },
//   { name: 'John', score: 85 },
//   { name: 'Zara', score: 74 }
// ]

Example 3: Sort by date

Suppose we have an array containing date strings that need to be sorted by date:

const dates = ['2023-03-15', '2021-06-01', '2022-12-25'];
((a, b) => new Date(a) - new Date(b));
(dates); 

// Output: ['2021-06-01', '2022-12-25', '2023-03-15']

8. Precautions and best practices

Consistency of array element types

Ensure that the elements in the array are consistent, otherwise the sorting results may not be as expected.

const mixed = [1, '2', 3, '10'];
();
(mixed);

// Output: [1, '10', 3, '2']

Use stable sorting

DefaultsortThe method is stable, i.e., for equal elements, their relative order remains the same. This is very important for certain scenarios (such as quadratic sorting).

Pay attention to performance

When processing large arrays,sortThe performance of the method may become a bottleneck. Although the V8 engine issortThe method is optimized, but in extreme cases, consider using a more efficient sorting algorithm or a strategy of dividing and conquering.

This is the end of this article about the detailed explanation of JavaScript sort sorting example. For more related JavaScript sorting content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!