mapNotNullish

import { mapNotNullish } from "jsr:@ende/collections";

function

function mapNotNullish<T, O>(array: Iterable<T>, transformer: (el: T, index: number) => O): NonNullable<O>[]

Returns a new array, containing all elements in the given array transformed using the given transformer, except the ones that were transformed to null or undefined.

array: Iterable<T>

The array to map elements from.

transformer: (el: T, index: number) => O

The function to transform each element. The function receives the element and its index.

Returns

A new array with all elements transformed by the given transformer, except the ones that were transformed to null or undefined.

Example: Basic usage

import { mapNotNullish } from "@ende/collections/map-not-nullish";
import { assertEquals } from "@ende/assert";

const people = [
  { middleName: null },
  { middleName: "William" },
  { middleName: undefined },
  { middleName: "Martha" },
];
const foundMiddleNames = mapNotNullish(people, (people) => people.middleName);

assertEquals(foundMiddleNames, ["William", "Martha"]);

Example: Using the index parameter

import { mapNotNullish } from "@ende/collections/map-not-nullish";
import { assertEquals } from "@ende/assert";

const values = [10, 20, 30, 40];
const result = mapNotNullish(values, (value, index) => index % 2 === 0 ? value : null);

assertEquals(result, [10, 30]);

Source