How to sort arrays of objects based on their properties using React and TypeScript

Post author: Adam VanBuskirk
Adam VanBuskirk
7/2/23 in
Tech
ReactTypeScript

The Client Code

const sortedLoads = sortArrayOfObjects(typeof sortField , sortDirection, sortField, loads);

The Sort Function

export const sortArrayOfObjects = (sortType: any, direction: string, field: string, collection: Array<any>) => {
    if (typeof sortType === "string") {
        if (direction === "asc") {
            collection.sort((a, b) => (a[field as keyof typeof a] > b[field as keyof typeof a]) ? 1 : ((b[field as keyof typeof a] > a[field as keyof typeof a]) ? -1 : 0));
        } else {
            collection.sort((a, b) => (b[field as keyof typeof a] > a[field as keyof typeof a]) ? 1 : ((a[field as keyof typeof a] > b[field as keyof typeof a]) ? -1 : 0));
        }
    } else {
        /* numeric and boolean */
        if (direction === "asc") {
            collection.sort((a, b) => a[field as keyof typeof a] - b[field as keyof typeof a]);
        } else {
            collection.sort((a, b) => b[field as keyof typeof a] - a[field as keyof typeof a]);
        }
    }
    const sortedCollection = [...collection];
    return sortedCollection;
}

Sign up today for our weekly newsletter about AI, SEO, and Entrepreneurship

Leave a Reply

Your email address will not be published. Required fields are marked *


Read Next




© 2024 Menyu LLC