When I'm sorting my array I get the following error in console:
Uncaught TypeError: Cannot read property 'localeCompare' of null
What I've tried so far:
HTML:
<table class="table table table-striped table-bordered table-hover" id="userLastSyncTable">
<thead>
<tr>
<th class="sortable sortDevicePlatform orderDevicePlatformByASC">Device Platform</th>
</tr>
</thead>
<tbody></tbody>
JavaScript/JQuery:
var TestArray = ["iOS 7", null, "iOS 8.4", null, null, null, "iOS 9"];
ShowUserSyncTable();
function ShowUserSyncTable() {
var tableRecord = '';
// Loop through all the returned records and add them to select box
for (var i = 0; i < TestArray.length; i++) {
tableRecord += "<tr id=" + "" + "><td>" + TestArray[i] + "</td></tr>";
}
$('#userLastSyncTable').find('tbody').html(tableRecord);
}
$(".sortDevicePlatform").click(function () {
var clickedDevicePlatformSorting = $(this).hasClass('orderDevicePlatformByASC') ? 'orderDevicePlatformByDESC' : 'orderDevicePlatformByASC';
$('.sortDevicePlatform').removeClass('orderDevicePlatformByASC').removeClass('orderDevicePlatformByDESC');
$('.sortDevicePlatform').addClass(clickedDevicePlatformSorting);
// Sort the sync list based on device platform
TestArray.sort(function (a, b) {
if (!a) {
// Change this values if you want to put `null` values at the end of the array
return -1;
}
if (!b) {
// Change this values if you want to put `null` values at the end of the array
return +1;
}
if (clickedDevicePlatformSorting == 'orderDevicePlatformByASC' && a) return a && b ? a.localeCompare(b) : -1;
else if (b) return a && b ? b.localeCompare(a) : 1;
});
ShowUserSyncTable();
});
How do I go about sorting the array with null values?
Update Fiddle for testing:
FIDDLE
Expected out come:
One click show:
iOS 7, iOS 8.4, iOS 9, null, null, null, null
Another click show:
iOS 9, iOS 8.4, iOS 7, null, null, null, null
You cannot call a function on null
. You have some null
values in your array. So when you try to sort
these values, it crashes.
You can protect your code to avoid that.
TestArray.sort(function(a, b) {
if (!a) {
// Change this values if you want to put `null` values at the end of the array
return -1;
}
if (!b) {
// Change this values if you want to put `null` values at the end of the array
return +1;
}
if (sorted)
return a.localeCompare(b);
else
return b.localeCompare(a);
});
But in my opinion, you should get rid of this null
values in the array. You can filter them :
TestArray = TestArray.filter(function(val) {
return val != null;
});
Try this: Demo.
Remove orderDevicePlatformByASC
class name from clickable <th ...>
. Because, its initial appearance is not sorted. Use this for sorting.
TestArray.sort(function (a, b) {
if (clickedDevicePlatformSorting == 'orderDevicePlatformByASC' && a)
return b ? a.localeCompare(b) : -1;
else if (b)
return a ? b.localeCompare(a) : 1;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With