• Sorts an array of objects by a given property in ascending or descending order.

    Remarks

    This function does not mutate the input array.

    Throws

    If the input array is null, undefined, or empty.

    Throws

    If the specified property to sort by does not exist in one or more of the objects in the array.

    Example

    Sort by age in ascending order:

    const users = [
    { name: 'John', age: 30 },
    { name: 'Alice', age: 25 },
    { name: 'Bob', age: 40 }
    ];

    sortBy(users, 'age', 'asc')
    // => { ok: true, value: [{ name: 'Bob', age: 20 }, { name: 'John', age: 25 }, { name: 'Alice', age: 30 }] }

    Example

    Sort by name in descending order:

    sortBy(arr, 'name', 'desc')
    // => { ok: true, value: [{ name: 'John', age: 25 }, { name: 'Bob', age: 20 }, { name: 'Alice', age: 30 }] }

    Example

    Sort by a nested property:

    const arr2 = [
    { name: 'John', address: { city: 'New York', state: 'NY' } },
    { name: 'Alice', address: { city: 'Los Angeles', state: 'CA' } },
    { name: 'Bob', address: { city: 'San Francisco', state: 'CA' } }
    ];

    sortBy(arr2, 'address.state', 'asc');
    // => { ok: true, value: [{ name: 'Alice', address: { city: 'Los Angeles', state: 'CA' } }, { name: 'Bob', address: { city: 'San Francisco', state: 'CA' } }, { name: 'John', address: { city: 'New York', state: 'NY' } }] }

    Type Parameters

    • const T extends Record<PropertyKey, any>

      The type of the objects in the array.

    Parameters

    • arr: T[]

      The array of objects to sort.

    • iteratee: string

      The property to sort the objects by. Can be a dot-separated string to group by a nested property, e.g. "prop1.prop2".

    • order: "asc" | "desc" = 'asc'

      The order to sort the objects in. Defaults to 'asc'. 'desc' for descending order.

    Returns Result<T[], Error>

    A Result object containing the sorted array on success, or an Error object on failure.

Generated using TypeDoc v0.24.7