For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /reference/object/sortKeys.md.

sortKeys es-toolkit

Creates a new object with the keys sorted.

const sorted = sortKeys(object);

Usage

sortKeys(object, compareKeys?)

Use sortKeys when you want to create a new object with its keys in a deterministic order. Keys are sorted alphabetically by default, which is useful for serialization, comparison, or display purposes.

import { sortKeys } from 'es-toolkit/object';

const sorted = sortKeys({ c: 3, a: 1, b: 2 });
// { a: 1, b: 2, c: 3 }

You can also provide a custom compare function for different sorting behavior.

// Sort in reverse alphabetical order
const reversed = sortKeys({ a: 1, b: 2, c: 3 }, (a, b) => b.localeCompare(a));
// { c: 3, b: 2, a: 1 }

Values are preserved as-is, including nested objects and arrays.

const obj = { z: [1, 2], a: { nested: true }, m: 'hello' };
const sorted = sortKeys(obj);
// { a: { nested: true }, m: 'hello', z: [1, 2] }

Parameters

objectTrequired

The object to sort keys from.

compareKeys(a: string, b: string) => numberoptional

A custom compare function for sorting keys. Defaults to alphabetical order.

Returns

A new object with the keys sorted.

T
Source: es-toolkit

Re-exported verbatim from es-toolkit. Implementation, edge cases, and performance behavior are owned upstream. This page mirrors the documentation at the pinned version; the linked source is authoritative.