Skip to content

filter() function

f가 truthy를 반환하는 모든 요소의 Iterable/AsyncIterable을 반환합니다.

Signature:

typescript
declare function filter<A>(
  f: BooleanConstructor,
  iterable: Iterable<A>,
): IterableIterator<TruthyTypesOf<A>>;

Example

ts
const iter = filter((a) => a % 2 === 0, [0, 1, 2, 3, 4, 5, 6]);
iter.next(); // {done:false, value: 0}
iter.next(); // {done:false, value: 2}
iter.next(); // {done:false, value: 4}
iter.next(); // {done:false, value: 6}
iter.next(); // {done:true, value: undefined}

// with pipe
pipe(
  [0, 1, 2, 3, 4, 5, 6],
  filter((a) => a % 2 === 0),
  toArray,
); // [0, 2, 4, 6]

await pipe(
  Promise.resolve([0, 1, 2, 3, 4, 5, 6]),
  filter((a) => a % 2 === 0),
  toArray,
); // [0, 2, 4, 6]

// if you want to use asynchronous callback
await pipe(
  Promise.resolve([0, 1, 2, 3, 4, 5, 6]),
  toAsync,
  filter(async (a) => a % 2 === 0),
  toArray,
); // [0, 2, 4, 6]

// toAsync
await pipe(
  [
    Promise.resolve(0),
    Promise.resolve(1),
    Promise.resolve(2),
    Promise.resolve(3),
    Promise.resolve(4),
    Promise.resolve(5),
    Promise.resolve(6),
  ],
  toAsync,
  filter((a) => a % 2 === 0),
  toArray,
); // [0, 2, 4, 6]

Try It

see pipe, toAsync, toArray

Open Source Code

Released under the Apache-2.0 License.