I have this method for sorting an array of objects, but when I have a complex structure, for example:
const data = [ { title: 'Book title', author: 'John', info: { language: english, pages: 500, price: '$50' }} ]
I can't sort the second level of the object 'info: {language: english, pages: 500, price:' $ 50 '}'
My Code:
import { useMemo, useState } from 'react';
interface SortConfigProps {
key: string;
direction: string;
}
export const useSortableData = <T>(items: T[]) => {
const [sortConfig, setSortConfig] = useState<SortConfigProps>(
{} as SortConfigProps,
);
const sortedItems = useMemo(() => {
const sortableItems = [...items];
if (sortConfig) {
sortableItems.sort((a: any, b: any) => {
if (a[sortConfig.key] < b[sortConfig.key]) {
return sortConfig.direction === 'ascending' ? -1 : 1;
}
if (a[sortConfig.key] > b[sortConfig.key]) {
return sortConfig.direction === 'ascending' ? 1 : -1;
}
return 0;
});
}
return sortableItems;
}, [items, sortConfig]);
const requestSort = (key: string) => {
let direction = 'ascending';
if (
sortConfig &&
sortConfig.key === key &&
sortConfig.direction === 'ascending'
) {
direction = 'descending';
}
setSortConfig({ key, direction });
};
return { items: sortedItems, requestSort, sortConfig };
};