# Swap two array items

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

Canonical: https://1loc.dev/array/swap-two-array-items/
Version: 1.0.0
Runtime: JavaScript · Node.js 22 / modern browsers
Verification: Local fixtures; no external services
Updated: 2026-10-28

## Implementation

```javascript
function swapItems({ values, i, j }) { const copy = [...values]; [copy[i], copy[j]] = [copy[j], copy[i]]; return copy; }
```

## Input

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

## Expected output

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

## Edge case

Input:
```json
{
  "values": [
    0,
    1
  ],
  "i": 0,
  "j": 1
}
```
Output:
```json
[
  1,
  0
]
```

## 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 lab validates types and size before calling this function. Add equivalent validation at your own trust boundary.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/swap-two-array-items.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: See original repository history
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: 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.
