import { useMemo, useState } from "react";
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];
}