Swap two array items
Return a copy with the items at i and j exchanged.
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.
Keep exploring
- Clone an array — Create a new array without copying the objects inside it.
- Remove duplicate values — Keep the first occurrence of each value, in its original order.
- Flatten a nested array — Turn a nested array into one sequence of values.