Sort the Contents of the table

Suseendra
featurepreneur
Published in
2 min readOct 30, 2022

We can sort the contents of the table by clicking the header, using javascript.

When the user clicks on a column header in the table, it will sort the contents in ascending and if the user clicks on the same column for the second time then sorts the contents in descending order.

$.each(properties, function (i, val) {

var orderClass = ‘’;

$(“#” + val).click(function (e) {

e.preventDefault();

$(‘.filter__link.filter__link — active’).not(this).removeClass(‘filter__link — active’);

$(this).toggleClass(‘filter__link — active’);

$(‘.filter__link’).removeClass(‘asc desc’);

if (orderClass == ‘desc’ || orderClass == ‘’) {

$(this).addClass(‘asc’);

orderClass = ‘asc’;

} else {

$(this).addClass(‘desc’);

orderClass = ‘desc’;

}

var parent = $(this).closest(‘.header__item’);

var index = $(“.header__item”).index(parent);

var $table = $(‘.table-content’);

var rows = $table.find(‘.table-row’).get();

var isSelected = $(this).hasClass(‘filter__link — active’);

var isNumber = $(this).hasClass(‘filter__link — number’);

rows.sort(function (a, b) {

var x = $(a).find(‘.table-data’).eq(index).text();

var y = $(b).find(‘.table-data’).eq(index).text();

if (isNumber == true) {

if (isSelected) {

return x — y;

} else {

return y — x;

}

} else {

if (isSelected) {

if (x < y) return -1;

if (x > y) return 1;

return 0;

} else {

if (x > y) return -1;

if (x < y) return 1;

return 0;

}

}

});

$.each(rows, function (index, row) {

$table.append(row);

});

return false;

});

});

The above code should be given within the script tag.

The asc function sorts in ascending order and the desc function sort in descending order.

When the user clicks the column for the first time it sorts the content in ascending order (i.e)(A-Z or 1–9).

When the user clicks for the second tie it sorts the content in descending order and the loop repeats.

Hope this article is useful!!!

--

--