AngularJS

UnderscoreJS – sortBy() Trick ::: It is not documented at their Site ! This is very important Shit !!!

In any programming language , Sorting is an extreme important part. In JavaScript , we need to do a lot.

Generally , we do Sorting for items like this a lot , like array containing multiple items(Numbers/Strings/Sometimes Objects etc).

 

1 var myNumberArray = [5,9,8,3,7,9];

UnderscoreJS is an awesome library which provide us so many small and important features to use.

Among those , Sorting is one . And by Underscore Sorting , we can Sort List of Objects to more than one degree. Means -Let We have a List of JSON Objects and that Object has multiple Properties(domain, url etc…) and we need to Sort the List as like –

First Sort the List based on domain and then url,it should be two degree.

Not like First sort the List based on domain and sort that result based on url,in this way we will get the wrong result.

Lets see the example below.

 1 var domainWithUrls =  [
 2             {domain:'abc.com' , url : 'abc.com/aaa.html'},
 3             {domain:'abc.com' , url : 'abc.com/ccc.html'},
 4             {domain:'abc.com' , url : 'abc.com/bbb.html'},
 5             {domain:'xyz.com' , url : 'xyz.com/aaa.html'},
 6             {domain:'xyz.com' , url : 'xyz.com/ccc.html'},
 7             {domain:'xyz.com' , url : 'xyz.com/bbb.html'},
 8             {domain:'pqr.com' , url : 'pqr.com/aaa.html'},
 9             {domain:'pqr.com' , url : 'pqr.com/ccc.html'},
10             {domain:'pqr.com' , url : 'pqr.com/bbb.html'}
11         ];
12 
13         var sortedItems = _.sortBy(domainWithUrls, function (obj) {
14             
15             return [obj.domain, obj.url];
16         });
17 
18         console.log(sortedItems);

And plz see the result in the image.

UnderscoreJS - sortBY() Trick

UnderscoreJS – sortBy() Trick

Unfortunately ,Though This multiple degree Sorting feature is available in UnderscoreJS , But this is not documented !!! Sad !!!

Its awesome and can save a good amount of development time . I needed this and dug into that , and discovered this awesome feature.Thought to share with you all.Hope , it helps.

Thanks.Cheers !!!

Standard

One thought on “UnderscoreJS – sortBy() Trick ::: It is not documented at their Site ! This is very important Shit !!!

Leave a Reply

Your email address will not be published. Required fields are marked *