Sort an array of items by given key

Return a copy sorted by one field, ascending.

JavaScript Version 1.0.0 · MIT · .md

sort-an-array-of-items-by-given-key.js
function sortBy({ values, key }) { return [...values].sort((a, b) => (a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0)); }

Input & expected output

Input

{
  "values": [
    {
      "status": "deferred"
    },
    {
      "status": "bounced"
    },
    {
      "status": "delivered"
    }
  ],
  "key": "status"
}

Expected output

[
  {
    "status": "bounced"
  },
  {
    "status": "deferred"
  },
  {
    "status": "delivered"
  }
]

The edge case

Input

{
  "values": [],
  "key": "status"
}

Expected output

[]

Know the limits

  • Mixed types compare unpredictably; keep the field one type.
  • Sorting is stable, so equal keys keep their order.

The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.

Source & maintenance

Based on Sort an array of items by given key from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.

Copies with spread instead of concat. Original MDX retained as inert source evidence.

Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.

Local fixture scope · Node.js 22.23.2 · reviewed October 28, 2026. No external service is required.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.