Home » Javascript » JavaScript sort array of object based on the value (conditional sorting)

JavaScript sort array of object based on the value (conditional sorting)

Posted by: admin August 19, 2018 Leave a comment

Questions:

I’ve an array like this:

[{"category_id":101,"category_name":"abc","state":null},
{"category_id":204,"category_name":"test","state":null},
{"category_id":7,"category_name":"pqr","state":"1526985908122"},
{"category_id":103,"category_name":"User","state":null},
{"category_id":2,"category_name":"System","state":null},
{"category_id":205,"category_name":"xyz","state":"1526985908019"},
{"category_id":203,"category_name":"dash","state":null},
{"category_id":4,"category_name":"hello","state":null},
{"category_id":206,"category_name":"demo","state":"1526985908187"},
{"category_id":6,"category_name":"about","state":null},
{"category_id":3,"category_name":"role","state":null}]

I want to sort this array based on the value of state property like you can see state has null and some numeric value here.

If state != null then sort in ascending order and
if state == null then sort in descending order (based on category id)

So the actual result should be like this:

[{"category_id":205,"category_name":"xyz","state":"1526985908019"},
{"category_id":7,"category_name":"pqr","state":"1526985908122"},
{"category_id":206,"category_name":"demo","state":"1526985908187"},
{"category_id":204,"category_name":"test","state":null},
{"category_id":203,"category_name":"dash","state":null},
{"category_id":103,"category_name":"User","state":null},
{"category_id":101,"category_name":"abc","state":null},
{"category_id":6,"category_name":"about","state":null},
{"category_id":4,"category_name":"hello","state":null},
{"category_id":3,"category_name":"role","state":null},
{"category_id":2,"category_name":"System","state":null}]

So it should sort first 3 records based on state value in ascending order and other records based on null value in descending order based on category id.

This is what I’ve tried referencing this article:
https://technology.amis.nl/2007/08/24/how-to-fix-your-number-sorting-problems-in-javascript/

var ALMOST_ZERO = -0.00000001;  
records.sort(function(a,b){         
    console.log(`comparing ${a.state},${b.state}`);
    var left = a.state != null ? a.state : ALMOST_ZERO;
    var right = b.state != null ? b.state : ALMOST_ZERO;    
    return right-left;
});

Any help would be appreciated.

Thanks

Answers: