moveElement
import { moveElement } from 'cx/data'; Copied moveElement moves an element from one position to another within an array, shifting other elements accordingly.
<div controller={PageController}>
<Grid
records={m.items}
selection={{ type: KeySelection, bind: m.selectedId, keyField: "id" }}
columns={[
{ header: "ID", field: "id", align: "center" },
{ header: "Name", field: "name" },
]}
/>
<div style="margin-top: 16px; display: flex; gap: 8px; flex-wrap: wrap">
<Button onClick="moveUp">Move Up</Button>
<Button onClick="moveDown">Move Down</Button>
<Button onClick="moveToTop">Move to Top</Button>
<Button onClick="moveToBottom">Move to Bottom</Button>
<Button onClick="reset">Reset</Button>
</div>
</div> | ID | Name |
|---|---|
| 1 | First |
| 2 | Second |
| 3 | Third |
| 4 | Fourth |
| 5 | Fifth |
Signature
function moveElement<T>(
array: T[],
sourceIndex: number,
targetIndex: number,
): T[];
Parameters
| Parameter | Type | Description |
|---|---|---|
array | T[] | The array to modify. |
sourceIndex | number | Index of the element to move. |
targetIndex | number | Target position (element will be placed before this index). |
Return Value
Returns a new array with the element moved. Returns the original array if source and target are the same.
Examples
Move element forward
const items = ["a", "b", "c", "d", "e"];
const result = moveElement(items, 1, 4);
// ["a", "c", "d", "b", "e"]
// "b" moved from index 1 to before index 4
Move element backward
const items = ["a", "b", "c", "d", "e"];
const result = moveElement(items, 3, 1);
// ["a", "d", "b", "c", "e"]
// "d" moved from index 3 to index 1
Move to beginning
const items = ["a", "b", "c", "d"];
const result = moveElement(items, 2, 0);
// ["c", "a", "b", "d"]
Move to end
const items = ["a", "b", "c", "d"];
const result = moveElement(items, 0, 4);
// ["b", "c", "d", "a"]
See Also
- insertElement - Insert new elements at position
- updateArray - Update and reorder items