Function uniqueByValue

Filters the input iterable, only yielding unique values. Use unique to compare by object reference instead.

Streaming: Works with unbounded iterables.

const d = ['a', 'b', 'c', 'b', 'd' ];
for (const v of uniqueByValue(d)) {
// Yields: 'a', 'b', 'c', 'd'
// (extra 'b' is skipped)
}

By default, JSON.stringify is used to create a string representing value. These are added to a Set of strings, which is how we keep track of uniqueness. If the value is already a string it is used as-is.

This allows you to have custom logic for what determines uniqueness. Eg, using a single field of an object as an identifier:

const people = [
{ name: `Mary`, size: 20 }, { name: `Abdul`, size: 19 }, { name: `Mary`, size: 5 }
]
for (const v of uniqueByValue(d, v=>v.name)) {
// Yields: { name: `Mary`, size: 20 }, { name: `Abdul`, size: 19 }
// Second 'Mary' is skipped because name is the same, even though size field is different.
}

If you want to keep track of the set of keys, or prime it with some existing data, provide a Set instance:

const unique = new Set();
unique.add(`b`);
const d = [`a`, `b`, `c`];
for (const v of uniqueByValue(d, toStringDefault, unique)) {
// Yields: `a`, `c`
// `b` is skipped because it was already in set
}
// After completion, `unique` contains `a`, `b` and `c`.

Creating your own Set is useful for tracking unique values across several calls to uniqueByValue.

  • Type Parameters

    • T

    Parameters

    • input: Iterable<T> | T[]
    • toString: ((v: T) => string)
        • (v): string
        • Parameters

          Returns string

    • Optionalseen: Set<string>

    Returns Generator<T>

  • Type Parameters

    • T

    Parameters

    • input: AsyncIterable<T>
    • toString: ((v: T) => string)
        • (v): string
        • Parameters

          Returns string

    • Optionalseen: Set<string>

    Returns AsyncGenerator<T>