Grid.js Library – Sorting issue for words/strings

|
| By Ishpreet Kaur

It is a library to show data in tabular form gracefully. It is a free and open-source javascript library plugin. Please check this link to work with the Grid.js library.

This library helps in sorting, searching, and styling tables without or with little effort.
Let’s have the following HTML and Javascript/jQuery code to get table data with the grid.js library.
Please add the required bootstrap and jquery cdn links to your file for this to work.

HTML Sample
<h3>Employee Information</h3>
<div id="gridtable"></div>

Grid.js javascript code
gridEmp = new gridjs.Grid({
columns: [
{
id: "id",
name: "Id",
hidden: true
},
{
id: "name",
name: "Name",
},
{
id: "city",
name: "City"
},
],
pagination: {limit: 10},
sort: !0,
search: !0,
resizable: true,
fixedHeader: !0,
data: () => getEmpData()
}).render(document.getElementById("gridtable"));

getEmpData() is a javascript function to get table data in json format. It can be achieved with ajax or fixed table data as per your requirement. data parameter for grid.js is used to pass json data and show data in table format.

For sample, let’s have data in following format:
function getEmpData() {
var tableData = [
{'id': 1, 'name': 'Emily', 'city': 'Amr'},
{'id': 2, 'name': 'aman', 'city': 'Ludhiana'},
{'id': 3, 'name': 'chhavi', 'city': 'ambala'},
{'id': 4, 'name': 'Tanveer', 'city': 'Chd'}
];
return tableData;
}

The above grid.js code will display html as shown below:
Grid.js Library

This library is perfect to work with. I face one issue with sorting this table. When I click on the arrow button of the Name column, the data is shown as follows:
gridjs1

In the above screenshot, we can see that Tanveer comes before aman. Technically, it may be correct as javascript, php or any other programming language first sorts the numbers, then capital letters, and then small letters. But, I face the requirement of sorting based on the alphabet irrespective of capital/small letters. So, I solve this problem by adding one more parameter to this column as shown below:
{
id: "name",
name: "Name",
sort: {
compare: (a, b) => {
a = a.toLowerCase();
b = b.toLowerCase();
if (a > b) {
return 1;
} else if (b > a) {
return -1;
} else {
return 0;
}
}
}
},

As you can see in the above code that, I have added a comparison logic by making all letters in lowercase and then following result comes:
gridjs2

So, you are ready to work with sorting for string data in this library.

Leave a Reply

Your email address will not be published. Required fields are marked *