oxc-project/oxc · error · OxcDiagnostic

Use `Array#toSorted()` instead of `Array#sort()`.

Error message

Use `Array#toSorted()` instead of `Array#sort()`.

What it means

Raised by unicorn/no-array-sort when `Array#sort()` is called (with ES2023 available). Since `sort()` mutates the array in place, the rule directs to the non-mutating variant; the faulting input is the `.sort()` call at the labeled span.

Source

Thrown at crates/oxc_linter/src/rules/unicorn/no_array_sort.rs:22

use oxc_ast::{
    AstKind,
    ast::{Argument, ArrayExpressionElement, Expression},
};
use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::Span;

use crate::{
    AstNode,
    ast_util::leftmost_identifier_reference,
    context::LintContext,
    rule::{DefaultRuleConfig, Rule},
    utils::is_import_symbol,
};

fn no_array_sort_diagnostic(span: Span) -> OxcDiagnostic {
    OxcDiagnostic::warn("Use `Array#toSorted()` instead of `Array#sort()`.")
        .with_help("`Array#sort()` mutates the original array. Use `Array#toSorted()` to return a new sorted array without modifying the original.")
        .with_label(span)
}

#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct NoArraySort {
    /// When set to `true` (default), allows `array.sort()` as an expression statement.
    /// Set to `false` to forbid `Array#sort()` even if it's an expression statement.
    ///
    /// Example of **incorrect** code for this rule with `allowExpressionStatement` set to `false`:
    /// ```js
    /// array.sort();
    /// ```
    allow_expression_statement: bool,

    /// When set to `true`, allows sorting a fresh array created by a spread, e.g. `[...iterable].sort()`.
    /// This avoids the double allocation of `toSorted()` when sorting an iterable such as a `Set`.

View on GitHub (pinned to e1e7af627c)

Solutions

  1. Use `array.toSorted()` to get a new sorted array leaving the original untouched
  2. Use `[...array].sort()` on older runtimes
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at crates/oxc_linter/src/rules/unicorn/no_array_sort.rs:22 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of oxc-project/oxc@e1e7af627c (2026-08-20). Data as JSON: /api/errors/7d7f7575b8ad1d02. Report an issue: GitHub.