admin管理员组文章数量:1345398
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 paring field have null values, sorting is not happening, how to fix this issue?
/
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];
});
}
}
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 paring field have null values, sorting is not happening, how to fix this issue?
http://jsfiddle/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];
});
}
}
Share
Improve this question
edited May 18, 2017 at 7:54
Mel
6,07510 gold badges40 silver badges42 bronze badges
asked Nov 15, 2013 at 19:24
Shebin MathewShebin Mathew
3181 gold badge7 silver badges19 bronze badges
1 Answer
Reset to default 10you can deal with the null values inside the p func:
arrToSort.sort(function (a, b) {
if (a[strObjParamToSortBy]==null) return 1
if (b[strObjParamToSortBy]==null) return 0
return a[strObjParamToSortBy] > b[strObjParamToSortBy];
});
本文标签: Javascript sort method handling null valuesStack Overflow
版权声明:本文标题:Javascript sort method handling null values - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743801162a2541339.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论