Swap two array items

Return a copy with the items at i and j exchanged.

JavaScript Version 1.0.0 · MIT · .md

swap-two-array-items.js
function swapItems({ values, i, j }) { const copy = [...values]; [copy[i], copy[j]] = [copy[j], copy[i]]; return copy; }

Input & expected output

Input

{
  "values": [
    "a",
    "b",
    "c",
    "d"
  ],
  "i": 0,
  "j": 3
}

Expected output

[
  "d",
  "b",
  "c",
  "a"
]

The edge case

Input

{
  "values": [
    0,
    1
  ],
  "i": 0,
  "j": 1
}

Expected output

[
  1,
  0
]

Know the limits

  • The original only swapped when both items were truthy, so arrays containing 0 or "" were returned unchanged. Destructuring swaps any values and works in either index 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 Swap two array items from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.

Rewritten with destructuring on a copy; the original returned the array unchanged when either item was falsy and required i < j. 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”.