CxJS

updateArray

import { updateArray } from 'cx/data'; Copied

updateArray performs immutable updates on arrays. It applies a callback to transform items, optionally filtering which items to update and which to remove. Returns the original array if no changes were made.

<div controller={PageController}>
  <Grid
    records={m.items}
    columns={[
      { header: "ID", field: "id", align: "center" },
      { header: "Name", field: "name" },
      { header: "Count", field: "count", align: "right" },
    ]}
  />
  <div style="margin-top: 16px; display: flex; gap: 8px; flex-wrap: wrap">
    <Button onClick="incrementAll">Increment All</Button>
    <Button onClick="incrementEven">Increment Even IDs</Button>
    <Button onClick="removeSmall">Remove Count &lt; 3</Button>
    <Button onClick="reset">Reset</Button>
  </div>
</div>
IDNameCount
1Apple5
2Banana3
3Cherry8
4Date2

Signature

function updateArray<T>(
  array: T[],
  updateCallback: (item: T, index: number) => T,
  itemFilter?: (item: T, index: number) => boolean,
  removeFilter?: (item: T, index: number) => boolean
): T[]

Parameters

ParameterTypeDescription
arrayT[]The array to update.
updateCallbackfunctionTransform function applied to each item (or filtered items).
itemFilterfunctionOptional. If provided, only items matching this filter are updated.
removeFilterfunctionOptional. Items matching this filter are removed from the result.

Return Value

Returns a new array with updates applied, or the original array if nothing changed (preserves reference equality).

Examples

Update all items

const items = [{ id: 1, count: 5 }, { id: 2, count: 3 }];

const updated = updateArray(items, (item) => ({
  ...item,
  count: item.count + 1,
}));
// [{ id: 1, count: 6 }, { id: 2, count: 4 }]

Update specific items

const items = [{ id: 1, count: 5 }, { id: 2, count: 3 }];

const updated = updateArray(
  items,
  (item) => ({ ...item, count: item.count * 2 }),
  (item) => item.id === 2, // only update item with id 2
);
// [{ id: 1, count: 5 }, { id: 2, count: 6 }]

Remove items while updating

const items = [{ id: 1, count: 5 }, { id: 2, count: 3 }];

const updated = updateArray(
  items,
  (item) => item,
  null, // no filter for updates
  (item) => item.count < 4, // remove items with count < 4
);
// [{ id: 1, count: 5 }]

See Also

  • filter - Immutable array filtering
  • append - Immutable array append