Categories: Development

Highlight max and min column with DataTables

Highlighting the max and min column in a table made with DataTables.

Using the initComplete option to call a function that sorts each column into an array and then check what index it is in the array to determine the maximum and minimum value.

[0] is the first (maximum) whilst [1] would be the second.

Finding the last vale which is the lowest (red) is done by counting the array and finding the index that is length – 1

$("#the-table-id").DataTable({
    paginate: false,
    bFilter: false,
    bInfo: false,
    scrollX: true,
    initComplete: function () {
        let api = this.api();
        api.columns(":not(:first)").every(function () {
            let col = this.index();
            let data = this.data()
                .unique()
                .map(function (value) {
                    return parseInt(value);
                })
                .toArray()
                .sort(function (a, b) {
                    return b - a;
                });

            let length = data.length;

            api.cells(null, col).every(function () {
                let cell = parseInt(this.data());
                if (cell === data[0]) {
                    $(this.node()).css("background-color", "rgb(172, 240, 172)");
                } else if (cell === data[length - 1]) {
                    $(this.node()).css("background-color", "rgba(255, 85, 85, 0.32)");
                }
            });
        });
    }
});

CodePen example:

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago