-
Hi In the examples, I see the usage of I'm aware that a function already exists by that name internally, but that seems to serve a different purpose. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Did you ever find something that worked? I had AI in cursor create something real quick that works pretty good. file: src/types/tantable.d.ts: import "@tanstack/react-table";
declare module "@tanstack/react-table" {
interface Column<TData extends RowData, TValue> {
getUniqueValues: () => (string | number)[];
}
} file: src/utils/tantable.ts import { Column, Table } from "@tanstack/react-table";
export function extendColumnWithUniqueValues<TData>(table: Table<TData>) {
// Add getUniqueValues method to each column
table.getAllColumns().forEach((column: Column<TData, unknown>) => {
if (!column.getUniqueValues) {
column.getUniqueValues = () => {
const values = new Set<string | number>();
table.getRowModel().rows.forEach((row) => {
const value = row.getValue(column.id);
if (value !== undefined && value !== null) {
values.add(value as string | number);
}
});
return Array.from(values).sort((a, b) => {
if (typeof a === "number" && typeof b === "number") {
return a - b;
}
return String(a).localeCompare(String(b));
});
};
}
});
} file: src/components/SearchPanel/MyTable.tsx import { ReactElement } from "react";
import {
useReactTable,
} from "@tanstack/react-table";
import { extendColumnWithUniqueValues } from "../../utils/tantable";
export default function MyTable({
params
}): ReactElement {
const table = useReactTable({
// TabStack table params
});
// Extend columns with getUniqueValues method
extendColumnWithUniqueValues(table);
// Example usage of getUniqueValues
table.getAllColumns().forEach((column) => {
if (column.getCanFilter()) {
console.log(`Unique values for ${column.id}:`, column.getUniqueValues());
}
});
} |
Beta Was this translation helpful? Give feedback.
I had changed my code so that I didn't need to get the unique values of a column. Instead, I handled this outside of Tanstack Table by creating an array of unique values manually based on the data.
However, there is now the option in Tanstack Table to add custom features. Your approach is fine, but here's a more native way to do it. (See the custom features docs: https://tanstack.com/table/latest/docs/guide/custom-features#createcolumn).
file: useTable.ts