CxJS

filter

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

filter performs immutable array filtering. Unlike native Array.filter(), it returns the original array reference if no items are removed, enabling efficient change detection.

<div controller={PageController}>
  <Grid
    records={m.items}
    columns={[
      { header: "ID", field: "id", align: "center" },
      { header: "Name", field: "name" },
      { header: "Value", field: "value", align: "right" },
    ]}
  />
  <div style="margin-top: 16px; display: flex; gap: 8px; align-items: center; flex-wrap: wrap">
    <span>Threshold:</span>
    <NumberField value={m.threshold} style="width: 60px" />
    <Button onClick="filterAboveThreshold">Keep ≥ Threshold</Button>
    <Button onClick="filterEvenIds">Keep Even IDs</Button>
    <Button onClick="reset">Reset</Button>
  </div>
</div>
IDNameValue
1Alpha10
2Beta25
3Gamma5
4Delta30
5Epsilon15
Threshold:

Signature

function filter<T>(
  array: T[],
  callback: (item: T, index: number, array: T[]) => boolean,
): T[];

Parameters

ParameterTypeDescription
arrayT[]The array to filter.
callbackfunctionPredicate function. Return true to keep item.

Return Value

Returns a new array with items that pass the test, or the original array if all items pass (preserves reference equality).

Examples

Basic usage

const items = [1, 2, 3, 4, 5];
const result = filter(items, (n) => n > 2);
// [3, 4, 5]

Reference preservation

const items = [1, 2, 3];

// All items pass - returns same reference
const result1 = filter(items, (n) => n > 0);
console.log(result1 === items); // true

// Some items removed - returns new array
const result2 = filter(items, (n) => n > 1);
console.log(result2 === items); // false

With null array

const result = filter(null, (n) => n > 0);
// null

Why Use This Instead of Array.filter()?

The native Array.filter() always returns a new array, even if no items are removed. This can cause unnecessary re-renders in reactive frameworks since reference equality checks fail.

const items = [1, 2, 3];

// Native filter - always new array
const native = items.filter((n) => n > 0);
console.log(native === items); // false (always)

// cx filter - preserves reference if unchanged
const cx = filter(items, (n) => n > 0);
console.log(cx === items); // true

See Also