Ussortby
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];
}
Lucas Juan