T
TanStack3y ago
fair-rose

Sorting with Headers generated from an Array

Hello! I'm currently learning how to implement a tanstack-table and I think I hit a wall. The app is basically a stat calculator and stat viewer for a game (Fire Emblem). I would love to know how to properly create a sort function from headers generated from an array. So my data has a CharData[] type.
type CharData = {
name: string;
growth: number[];
mods: number[];
};
type CharData = {
name: string;
growth: number[];
mods: number[];
};
This is how I made the columns.
const tableHeaders = [
'HP',
'STR',
'MAG',
'DEX',
'SPD',
'DEF',
'RES',
'LCK',
'BLD',
'RTG',
];

const columns = [
columnHelper.accessor('name', { header: 'Name' }),
...tableHeaders.map((val, index) =>
columnHelper.accessor('growth', {
cell: (t) => t.getValue()[index],
header: () => val,
})
),
];
const tableHeaders = [
'HP',
'STR',
'MAG',
'DEX',
'SPD',
'DEF',
'RES',
'LCK',
'BLD',
'RTG',
];

const columns = [
columnHelper.accessor('name', { header: 'Name' }),
...tableHeaders.map((val, index) =>
columnHelper.accessor('growth', {
cell: (t) => t.getValue()[index],
header: () => val,
})
),
];
I already generated the table and it shows the whole data properly. It makes growth headers to become HP, STR, SKL, etc headers. So the table has Name & 10 other column headers generated from the growth.
Now I am trying to make sorting work and only the Name and HP columns work. If I click the others like STR, the sort is based on HP data. Any help would be greatly appreciated. Here is a preview link: https://fengage-calc-552xxrmp4-bananabread08.vercel.app/characters A branch of the working version: https://fengage-calc-5wgikp0dx-bananabread08.vercel.app/characters
FEngage Calc
Stat Growth Calculator for Fire Emblem: Engage
FEngage Calc
Stat Growth Calculator for Fire Emblem: Engage
2 Replies
deep-jade
deep-jade3y ago
i think the sorting is based on the acessorKey, so as you have one key 'growth' for every header it's sorting based on the first value hp
fair-rose
fair-roseOP3y ago
You're right mate! Thanks! solved! changed the data structure as a whole. growth is now an object that has HP, STR, etc keys.This way, it's easier to make the growth columns and also easier access to each cell value. It's working now Thanks for the suggestion imnsbay!

Did you find this page helpful?