Javascript dynamic sorting array of object include nulls while sorting

I have array of objects. It can contain string and Integer. I want to sort it based on property ,

In one of the sorting order(asc/desc) nulls should come first.

When property is not present or null in the array it should consider it as null. Like in some of the elements age is not defined or last name is missing

example of the array is this

function dynamicsort(property,order) {
    var sort_order = 1;
    if(order === "desc"){
        sort_order = -1;
    }
    return function (a, b){
        // a should come before b in the sorted order
        if(a[property] < b[property]){
                return -1 * sort_order;
        // a should come after b in the sorted order
        }else if(a[property] > b[property]){
                return 1 * sort_order;
        // a and b are the same
        }else{
                return 0 * sort_order;
        }
    }
}
let employees = [
    {
        firstName: 'John',
        age: 27,
        joinedDate: 'December 15, 2017'
    },

    {
        firstName: 'Ana',
        lastName: 'Rosy',
        age: 25,
        joinedDate: 'January 15, 2019'
    },

    {
        firstName: 'Zion',
        lastName: 'Albert',
        age: 30,
        joinedDate: 'February 15, 2011'
    },
    {
        firstName: 'ben',
        lastName: 'Doe',
        joinedDate: 'December 15, 2017'
    },
    {
        firstName: 'Tom',
        lastName: 'Doe',
        joinedDate: 'December 15, 2017'
    },
];

console.log("Object to be sorted");
console.log(employees);
console.log("Sorting based on the age property")
console.log(employees.sort(dynamicsort("age","desc")));
console.log("Sorting based on the age property")
console.log(employees.sort(dynamicsort("age","asc")));

console.log("Sorting based on the lastName property")
console.log(employees.sort(dynamicsort("lastName","desc")));
console.log("Sorting based on the lastName property")
console.log(employees.sort(dynamicsort("lastName","asc")));

Source: Ask Javascript Questions

LEAVE A COMMENT