6

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];
        });
    }
}

1 Answer 1

10

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];
    });
Sign up to request clarification or add additional context in comments.

5 Comments

can I get objects with null values at the end of the sorted list? Thanks.
Set the first condition to if(a[strObjParamToSortBy] == null) return -1; jsfiddle.net/kv8hp/2
I am sorry but multiple null objects are not displaying in result only one is coming jsfiddle.net/mailtoshebin/kv8hp/3
jsfiddle.net/nQkBj is working fine but only one null object is showing inside result
Perhaps I misunderstand your question... I updated the fiddle to include two null values. I also changed the alert to include all of the elements in the array. Both null values appear at the end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.