insertElement
import { insertElement } from 'cx/data'; Copied insertElement inserts one or more elements at a specific position in an array.
<div controller={PageController}>
<Grid
records={m.items}
columns={[
{ header: "#", field: "$index", align: "center" },
{ header: "ID", field: "id", align: "center" },
{ header: "Name", field: "name" },
]}
/>
<div style="margin-top: 16px; display: flex; gap: 8px; align-items: center; flex-wrap: wrap">
<span>Index:</span>
<NumberField value={m.insertIndex} style="width: 50px" />
<TextField value={m.newName} style="width: 100px" />
<Button onClick="insertItem">Insert</Button>
<Button onClick="insertMultiple">Insert Multiple</Button>
<Button onClick="reset">Reset</Button>
</div>
</div> | # | ID | Name |
|---|---|---|
| 1 | First | |
| 2 | Second | |
| 3 | Third |
Index:
Signature
function insertElement<T>(array: T[], index: number, ...elements: T[]): T[];
Parameters
| Parameter | Type | Description |
|---|---|---|
array | T[] | The array to insert into. |
index | number | Position to insert at. |
elements | T[] | Elements to insert. |
Return Value
Returns a new array with elements inserted at the specified position.
Examples
Insert single element
const items = ["a", "b", "c"];
const result = insertElement(items, 1, "x");
// ["a", "x", "b", "c"]
Insert multiple elements
const items = ["a", "b", "c"];
const result = insertElement(items, 1, "x", "y");
// ["a", "x", "y", "b", "c"]
Insert at beginning
const items = ["a", "b", "c"];
const result = insertElement(items, 0, "x");
// ["x", "a", "b", "c"]
Insert at end
const items = ["a", "b", "c"];
const result = insertElement(items, 3, "x");
// ["a", "b", "c", "x"]
See Also
- append - Add elements to end of array
- moveElement - Move element within array