move
Returns a new array with an element moved from one index to another. If from
or to
is out of bounds, the original array is returned unchanged.
1/**
2 * Returns a new array with an element moved from one index to another.
3 * If 'from' or 'to' is out of bounds, the original array is returned unchanged.
4 *
5 * @param arr - Source array.
6 * @param from - Index of the item to move.
7 * @param to - Target index to move the item to.
8 * @returns A new array with the element repositioned.
9 */
10export function move<T>(arr: T[], from: number, to: number): T[] {
11 if (
12 from < 0 || from >= arr.length ||
13 to < 0 || to >= arr.length ||
14 from === to
15 ) {
16 return [...arr]; // no-op or invalid
17 }
18
19 const copy = [...arr];
20 const [item] = copy.splice(from, 1);
21 copy.splice(to, 0, item);
22 return copy;
23}
Immutable implementation
Returns a new array without modifying the original input, enabling safe functional patterns.
Built-in boundary validation
Gracefully handles edge cases (invalid indices or
from === to
) by returning an unchanged copy of the original array.Minimal and efficient logic
Utilizes
splice
effectively for both removal and insertion in a concise and performant way.Index-safe logic
Prevents runtime errors that could arise from negative indices or overshooting the array bounds.
Type-safe
Fully generic and preserves the input type across the returned array.
Tests | Examples
1test('move - basic move forward', () => {
2 expect(move([1, 2, 3], 0, 2)).toEqual([2, 3, 1]);
3});
4
5test('move - basic move backward', () => {
6 expect(move([1, 2, 3], 2, 0)).toEqual([3, 1, 2]);
7});
8
9test('move - same index', () => {
10 expect(move([1, 2, 3], 1, 1)).toEqual([1, 2, 3]);
11});
12
13test('move - invalid indices (out of bounds)', () => {
14 expect(move([1, 2, 3], -1, 1)).toEqual([1, 2, 3]);
15 expect(move([1, 2, 3], 1, 5)).toEqual([1, 2, 3]);
16});
17
18test('move - single item array', () => {
19 expect(move([1], 0, 0)).toEqual([1]);
20});
Common Use Cases
Reordering UI elements
Useful in drag-and-drop interfaces for rearranging items (e.g., cards, lists, rows, tabs).
Custom sorting or prioritization
Repositions elements to reflect changes in user preference or business rules.
Queue or stack manipulation
Enables flexible control over the order of operations or tasks.
Game development
Can help manage the order of players, cards, or game entities based on game state transitions.
Data transformation pipelines
Used to rearrange datasets or schema representations during pre-processing.