Function uniqueObjectArray

  • Filters an array of objects such that only unique versions of the objects exist within the new array. A given object instance is considered unique based on the value of an object property that should indicate uniqueness. The function returns a copy of the array where only one instance (the first instance) of a given object with the uniqueProperty value exists. For eg:

    const arr = [
    { name: "A", size: 12 },
    { name: "B", size: 11 },
    { name: "C", size: 12 },
    { name: "B", size: 15 },
    ];

    uniqueObjectArray(arr, "name")
    uniqueObjectArray(arr, "size")

    Should result, respectively, in:

    [
    { name: "A", size: 12 },
    { name: "B", size: 11 },
    { name: "C", size: 12 },
    ]

    and

    • ``` javascript

    [ { name: "A", size: 12 }, { name: "B", size: 11 }, { name: "B", size: 15 }, ]


    Or perhaps a more realistic example, to ensure we only have one version of a
    given person in an array, filter based on their ID number, which should be
    a unique identifier:

    ```javascript
    const people = [
    { name: "Andrew", idNumber: "1234" },
    { name: "John", idNumber: "4567" },
    { name: "Joe", idNumber: "8910" },
    { name: "John", idNumber: "4567" },
    ];

    uniqueObjectArray(arr, "idNumber")

    Will return a new array where only one version of John exists.

    Returns

    Returns the unique object array

    Type Parameters

    • T

    Parameters

    • arr: T[]
    • uniqueProperty: string

    Returns T[]

Generated using TypeDoc