distinctBy

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

function

function distinctBy<T, D>(array: Iterable<T>, discriminator: (el: T, index: number) => D): T[]

Returns all elements in the given array that produce a unique value using the given discriminator, with the first matching occurrence retained.

Uniqueness is determined by same-value-zero equality of the returned values.

array: Iterable<T>

The array to filter for distinct elements.

discriminator: (el: T, index: number) => D

The function to extract the value to compare for uniqueness. The function receives the element and its index.

Returns

An array of distinct elements in the input array.

Example: Basic usage

import { distinctBy } from "@ende/collections/distinct-by";
import { assertEquals } from "@ende/assert";

const users = [{ id: 1, name: "Anna" }, { id: 2, name: "Kim" }, { id: 1, name: "Anna again" }];
const uniqueUsers = distinctBy(users, (user) => user.id);

assertEquals(uniqueUsers, [{ id: 1, name: "Anna" }, { id: 2, name: "Kim" }]);

Example: Using the index parameter

import { distinctBy } from "@ende/collections/distinct-by";
import { assertEquals } from "@ende/assert";

const items = [25, "asdf", true];
const result = distinctBy(items, (_, index) => index > 1);

assertEquals(result, [25, true]);

Source