Skip to content

select

Filters and transforms an array in a single pass.

Similar to .filter(condition).map(mapper) but iterates the array only once. Index semantics differ from .filter().map(): the index passed to both condition and mapper is the index in the original array, not the post-filter position. Use index-agnostic callbacks when the two must behave identically.

Available since v2.0.3

import { select } from '@helpers4/array';
// or, from the all-in-one package (same code, one install):
import { select } from 'helpers4/array';
select<T, U>(array: readonly T[] | null | undefined, mapper: function, condition: function): U[]
ParameterTypeDescription
arrayreadonly T[] | null | undefinedThe array to process
mapperfunctionTransforms each item that passes the condition
conditionfunctionDetermines which items to include; defaults to keeping all items

U[] — Mapped values for items that pass the condition

Keeps only items matching the condition and transforms them — equivalent to .filter().map() but with a single iteration.

select([1, 2, 3, 4, 5], x => x * 2, x => x % 2 === 0)
// => [4, 8]

Filter on a condition and pluck a specific property in a single readable call.

const users = [
  { name: 'Alice', active: true },
  { name: 'Bob',   active: false },
  { name: 'Carol', active: true },
];
select(users, u => u.name, u => u.active)
// => ['Alice', 'Carol']

View source on GitHub