Search
 
SCRIPT & CODE EXAMPLE
 

TYPESCRIPT

useSortBy

import { useMemo, useState } from "react";

/**
 * @example
 * const array = [{name: 'b'}, {name: 'a'}]
 * const sortedArray = useSortBy(array, 'name')
 * console.log(sortedArray)
 * // [{name: 'a'}, {name: 'b'}]
 */
export const useSortBy = (data: any[], key: string, direction: "asc" | "desc" = "asc"): Array<any> => {
    const [sortKey, setSortKey] = useState(key);
    const [sortDirection, setSortDirection] = useState(direction);

    const sortArray = useMemo(() => {
        return data.sort((a, b) => {
            if (a[sortKey] < b[sortKey]) {
                return sortDirection === "asc" ? -1 : 1;
            }
            if (a[sortKey] > b[sortKey]) {
                return sortDirection === "asc" ? 1 : -1;
            }
            return 0;
        });
    }, [data, sortDirection, sortKey]);

    return [sortArray, setSortKey, setSortDirection];
}
Comment

PREVIOUS NEXT
Code Example
Typescript :: e.target.value typescript 
Typescript :: cant find the name console 
Typescript :: An unhandled exception occurred: Schematic "Module" not found in collection "@schematics/angular". 
Typescript :: check if an element exists laravel 
Typescript :: compare 2 sets python 
Typescript :: .for each typescript 
Typescript :: what are the benefits of linux 
Typescript :: paste elements of a vector r 
Typescript :: sprockets cannot load such file sass 
Typescript :: how many elements can be stored in an array 
Typescript :: vscode pass argument to registerCommand 
Typescript :: optional or required depending on param is true react typescript 
Typescript :: use curly brackets in latex 
Typescript :: How to reuse parts of Eloquent builder in Laravel 
Typescript :: What are the components of the environment? Explain it along with the examples class 6 
Typescript :: can subclass method infere exceptions of its superclass method 
Typescript :: custom function with condition in google sheet 
Typescript :: whats the next sonic game 
Typescript :: c code for insrting elements in set 
Typescript :: ignoring header x-firebase-locale because its value was null. flutter 
Typescript :: requests session next page python 
Typescript :: get all fields of mongoose schema typescript 
Typescript :: pull rewuests in local project 
Typescript :: endurance testing 
Typescript :: how to concate a string to all elements in a list in python 
Typescript :: where to put toaster on http service calls typescript 
Cpp :: dart and or 
Cpp :: c++ - include all libraries 
Cpp :: 2d vector print 
Cpp :: get current date in c++ 
ADD CONTENT
Topic
Content
Source link
Name
8+9 =