# sort-object-keys

> Sort an object's keys, including an optional key list

Latest version **2.1.0** (published 2026-01-12) · MIT license · 0 weekly downloads

## Install

```sh
npm install sort-object-keys
pnpm add sort-object-keys
yarn add sort-object-keys
bun add sort-object-keys
```

## Health

**Score 65/100 (B)** — status: stable.

Positive: has types; esm support; no vulnerabilities; has provenance; high quality score.

Warnings: low downloads.

## Facts

| | |
|---|---|
| Version | 2.1.0 |
| Published | 2026-01-12 |
| First published | 2015-11-30 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 0 |
| Unpacked size | 3.3 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Provenance | attested (GitHub Actions) |
| GitHub stars | 34 |
| Author | Keith Cirkel |
| Maintainers | keithamus |
| Keywords | keys, object, sort |

## Links

- npm: https://www.npmjs.com/package/sort-object-keys
- Repository: https://github.com/keithamus/sort-object-keys
- Homepage: https://github.com/keithamus/sort-object-keys#readme
- Issues: https://github.com/keithamus/sort-object-keys/issues
- npm.io page: https://npm.io/package/sort-object-keys

## Recent versions

- 2.1.0 (latest) — 2026-01-12
- 2.0.1 — 2025-10-30
- 2.0.0 — 2025-09-16
- 1.1.3 — 2019-12-10
- 1.1.2 — 2015-12-14
- 1.1.1 — 2015-12-02
- 1.1.0 — 2015-12-02
- 1.0.0 — 2015-11-30

## README

# Sort Object

[![Build Status](https://travis-ci.org/keithamus/sort-object-keys.svg)](https://travis-ci.org/keithamus/sort-object-keys)

Returns a copy of an object with all keys sorted.

The second argument is optional and is used for ordering - to provide custom sorts. You can either pass an array containing ordered keys or a function to sort the keys (same signature as in [`Array.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)).

```js
import assert from 'assert'
import sortObject from 'sort-object-keys'

assert.equal(
  JSON.stringify({
    c: 1,
    b: 1,
    d: 1,
    a: 1,
  }),
  JSON.stringify({
    a: 1,
    b: 1,
    c: 1,
    d: 1,
  }),
)

assert.equal(
  JSON.stringify(
    sortObject(
      {
        c: 1,
        b: 1,
        d: 1,
        a: 1,
      },
      ['b', 'a', 'd', 'c'],
    ),
  ),
  JSON.stringify({
    b: 1,
    a: 1,
    d: 1,
    c: 1,
  }),
)

function removeKeyAncCompareIndex(keyA, keyB) {
  var a = parseInt(keyA.slice(4))
  var b = parseInt(keyB.slice(4))
  return a - b
}

assert.equal(
  JSON.stringify(
    sortObject(
      {
        'key-1': 1,
        'key-3': 1,
        'key-10': 1,
        'key-2': 1,
      },
      removeKeyAncCompareIndex,
    ),
  ),
  JSON.stringify({
    'key-1': 1,
    'key-2': 1,
    'key-3': 1,
    'key-10': 1,
  }),
)
```

---
_Source: https://npm.io/package/sort-object-keys · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
