CxJS

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>
#IDName
1First
2Second
3Third
Index:

Signature

function insertElement<T>(array: T[], index: number, ...elements: T[]): T[];

Parameters

ParameterTypeDescription
arrayT[]The array to insert into.
indexnumberPosition to insert at.
elementsT[]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