I have a list of objects where I want to sort the objects based on a field I know I can use sort methods. When the comparing field have null values, sorting is not happening, how to fix this issue?
http://jsfiddle.net/mailtoshebin/kv8hp/
var arrOfObj = [
{
"Name": "Zak",
"Age": 25
},
{
"Name": "Adel",
"Age": 38
},
{
"Name": null,
"Age": 38
},
{
"Name": "Yori",
"Age": 28
}
];
sortArrOfObjectsByParam(arrOfObj, "Name");
alert("ASCENDING: " + arrOfObj[0].Name + ", " + arrOfObj[1].Name + ", " + arrOfObj[2].Name);
function sortArrOfObjectsByParam(arrToSort , strObjParamToSortBy ) {
if(sortAscending == undefined) sortAscending = true; // default to true
if(sortAscending) {
arrToSort.sort(function (a, b) {
return a[strObjParamToSortBy] > b[strObjParamToSortBy];
});
}
else {
arrToSort.sort(function (a, b) {
return a[strObjParamToSortBy] < b[strObjParamToSortBy];
});
}
}
If you specify the ORDER BY clause, NULL values by default are ordered as less than values that are not NULL. Using the ASC order, a NULL value comes before any non-NULL value; using DESC order, the NULL comes last.
The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
you can deal with the null values inside the comp func:
arrToSort.sort(function (a, b) {
if (a[strObjParamToSortBy]==null) return 1
if (b[strObjParamToSortBy]==null) return 0
return a[strObjParamToSortBy] > b[strObjParamToSortBy];
});
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