---
id: javascript-array-sort
title: "JavaScript Array Sort"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["Array sort", "sort()", "reverse()", "toSorted", "compare function", "numeric sort"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.9
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "array", "sort"]
raw_sources: ["https://www.w3schools.com/js/js_array_sort.asp"]
applied_in: []
github_commit: ""
---

# [[JavaScript Array Sort]]

## 🎯 한 줄 통찰 (One-line insight)
`sort()` orders array elements alphabetically by default (treating them as strings), so numeric sorting requires a compare function `(a, b) => a - b`; ES2023's `toSorted()`/`toReversed()` provide non-mutating alternatives. [S1]

## 🧠 핵심 개념 (Core concepts)
- **`sort()`** sorts an array alphabetically (as strings) and mutates the original array. [S1]
- **`reverse()`** reverses the order of the elements in an array; combining `sort()` then `reverse()` produces descending alphabetical order. [S1]
- **`toSorted()`** (ES2023) returns a new sorted array, leaving the original unchanged. [S1]
- **`toReversed()`** (ES2023) returns a new reversed array, leaving the original unchanged. [S1]
- **Default sort is string-based** — so `"25"` sorts higher than `"100"` because "2" is greater than "1"; numeric sorting needs a compare function. [S1]
- **The compare function** returns a negative value (sort `a` before `b`), a positive value (sort `b` before `a`), or zero (no change). [S1]
- **Sorting is stable** as of the ES2019 standard requirement. [S1]

## 🧩 추출된 패턴 (Extracted patterns)
- **Numeric ascending** — `arr.sort((a, b) => a - b)`. [S1]
- **Numeric descending** — `arr.sort((a, b) => b - a)`. [S1]
- **Min/max via sort** — sort numerically, then read the first or last element. [S1]
- **Min/max via Math.apply** — `Math.min.apply(null, arr)` / `Math.max.apply(null, arr)`. [S1]
- **Sort objects by property** — pass a compare function reading the property (numeric `a.prop - b.prop`, or string comparison with `toLowerCase()`). [S1]

## 📖 세부 내용 (Details)
**Sorting an Array** — The `sort()` method sorts an array alphabetically: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
```

**Reversing an Array** — The `reverse()` method reverses the elements in an array: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.reverse();
```

By combining `sort()` and `reverse()`, you can sort an array in descending order: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
```

**The toSorted() Method** (ES2023) — provides a safe way of sorting an array without altering the original: [S1]
```javascript
const months = ["Jan", "Feb", "Mar", "Apr"];
const sorted = months.toSorted();
```

**The toReversed() Method** (ES2023) — reverses without altering the original: [S1]
```javascript
const months = ["Jan", "Feb", "Mar", "Apr"];
const reversed = months.toReversed();
```

**Numeric Sort** — By default, the `sort()` function sorts values as strings, so "25" is bigger than "100" because "2" is bigger than "1". A compare function fixes this. Ascending: [S1]
```javascript
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
```
Descending: [S1]
```javascript
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
```

**Sorting an Array in Random Order** — [S1]
```javascript
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(){return 0.5 - Math.random()});
```

**The Fisher Yates Method** — a more correct way to shuffle: [S1]
```javascript
const points = [40, 100, 1, 5, 25, 10];

for (let i = points.length -1; i > 0; i--) {
  let j = Math.floor(Math.random() * (i+1));
  let k = points[i];
  points[i] = points[j];
  points[j] = k;
}
```

**Find the Lowest (or Highest) Array Value** — using `Math.min.apply`: [S1]
```javascript
function myArrayMin(arr) {
  return Math.min.apply(null, arr);
}
```
Using `Math.max.apply`: [S1]
```javascript
function myArrayMax(arr) {
  return Math.max.apply(null, arr);
}
```

A custom minimum function (fastest method): [S1]
```javascript
function myArrayMin(arr) {
  let len = arr.length;
  let min = Infinity;
  while (len--) {
    if (arr[len] < min) {
      min = arr[len];
    }
  }
  return min;
}
```
A custom maximum function: [S1]
```javascript
function myArrayMax(arr) {
  let len = arr.length;
  let max = -Infinity;
  while (len--) {
    if (arr[len] > max) {
      max = arr[len];
    }
  }
  return max;
}
```

**Sorting Object Arrays** — JavaScript arrays often contain objects. Even if objects have properties of different data types, `sort()` can be used to sort the array, using a compare function for the property. By numeric property: [S1]
```javascript
cars.sort(function(a, b){return a.year - b.year});
```
By string property: [S1]
```javascript
cars.sort(function(a, b){
  let x = a.type.toLowerCase();
  let y = b.type.toLowerCase();
  if (x < y) {return -1;}
  if (x > y) {return 1;}
  return 0;
});
```

**Stable Sort** — As of the ES2019 standard, sorting is required to be stable: elements with equal sort keys keep their relative order. [S1]

## 🛠️ 적용 사례 (Applied in summary)
The page's own snippets are the canonical applied examples — sorting fruit names, numeric points ascending/descending, shuffling, finding min/max, and sorting car objects by `year` or `type`. No external project/commit applications found in the source.

## 💻 코드 패턴 (Code patterns)
Alphabetical sort:
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
```
Numeric sort ascending / descending:
```javascript
points.sort((a, b) => a - b);  // ascending
points.sort((a, b) => b - a);  // descending
```
Non-mutating (ES2023):
```javascript
const sorted = months.toSorted();
const reversed = months.toReversed();
```
Sort objects by numeric property:
```javascript
cars.sort(function(a, b){return a.year - b.year});
```

## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **`sort()`/`reverse()` vs `toSorted()`/`toReversed()`** — the former mutate the original array in place; the latter (ES2023) return new arrays and leave the original intact. Choose the non-mutating versions when you must preserve the source. [S1]
- **Random sort vs Fisher-Yates** — `sort(() => 0.5 - Math.random())` is shown but the page presents the Fisher-Yates loop as the more correct shuffle. [S1]
- **Min/max approaches** — sort-and-read, `Math.min/max.apply`, or a custom loop; the page notes the custom loop is the fastest. [S1]

## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source. The source notes that stable sorting became a requirement in the ES2019 standard and that `toSorted`/`toReversed` were added in ES2023. [S1]

## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.90
- **중복 검사 결과:** 신규 생성 (New discovery)

## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Array Search]], [[JavaScript Array Iteration]], [[JavaScript Math]]
- **참조 맥락:** Referenced whenever array elements must be ordered, shuffled, or reduced to a min/max value.

## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Array Sort — https://www.w3schools.com/js/js_array_sort.asp

## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Array Sort" page (Astra wiki-curation, P-Reinforce v3.1 format).
