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 < 3</Button>
<Button onClick="reset">Reset</Button>
</div>
</div> | ID | Name | Count |
|---|---|---|
| 1 | Apple | 5 |
| 2 | Banana | 3 |
| 3 | Cherry | 8 |
| 4 | Date | 2 |
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
| Parameter | Type | Description |
|---|---|---|
array | T[] | The array to update. |
updateCallback | function | Transform function applied to each item (or filtered items). |
itemFilter | function | Optional. If provided, only items matching this filter are updated. |
removeFilter | function | Optional. 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 }]