How to specify column order

How to specify column order

gb691gb691 Posts: 10Questions: 4Answers: 0
edited August 28 in Free community support

Hi,

I'm getting input from a user via a dropdown, they can select employees or managers, which will run 2 separate SQL queries depending on which option was chosen and return the results as JSON data. The 2 datasets have many of the same columns, with only a handful unique to each, so in my javascript I've specified 2 variables to hold the "common" and "unique" columns and have then spread them in the columns property.

However, the columns appear in the datatable as per the order of the columns array, so my unique columns are appearing at the end currently, which is not what I want.

Is there a way within the column object itself to define its position in the table? E.g.

{
        data: "id",
        title: "Employee ID",
        visible: true,
        position: 0
}

Kind regards,
Guy

const commonColumns = [         
    { 
        data: "firstName",
        title: "First Name",
        visible: true
    },
    { 
        data: "lastName",
        title: "Last Name",
        visible: true
    },
    { 
        data: "age",
        title: "Age",
        visible: true
    }
    etc...
];


const uniqueColumns = {
    'EMP' : [
        {
            data: "id",
            title: "Employee ID",
            visible: true
        },
        {
            data: "manager",
            title: "Manager",
            visible: true
        }
    ],
    'MAN' : [
        {
            data: "teamName",
            title: "Team Name",
            visible: true
        },
        {
            data: "budget",
            title: "Budget",
            visible: true
        }
        etc...
    ]
}


...
columns: [
    ...commonColumns,
    ...uniqueColumns[cohortSelected]
],
...

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 65,972Questions: 1Answers: 10,980 Site admin
    Answer ✓

    However, the columns appear in the datatable as per the order of the columns array, so my unique columns are appearing at the end currently, which is not what I want.

    You need to reorder the columns array into the order that you want them to appear. You could use .sort() with a custom function on the array if you know what the order should be (you could add an order property to the array elements I guess).

    Is there a way within the column object itself to define its position in the table?

    No - the order given to DataTables is the order the columns will be. As I say, you need to reorder the items in the array. Either change how you construct the array or add a property and then order the array on it.

    Allan

Sign In or Register to comment.