I need to sort an array of object literals and I need to compare 2 of the object’s properties. I found an example online of how to do it but I couldn’t find any supporting documentation in the spec. Can anyone confirm that you can do the following in Javascript and possibly point me to some documentation:
users.sort(function(a, b){
return [a.name, a.company] > [b.name, b.company] ? 1:-1;
});
Edit: I now get why this is working, it’s because it’s simply concatenating and then comparing the strings. I don’t think the intention is very clear so I’ll probably write something a little less hacky.
Also, I wasn’t simply asking if you could create a custom sort function, that you can easily find in the docs. I was asking if the way I was doing it in this particular case is valid.
As I already explained in the comments, yes, you could do it like that.
What is happening here?
Whenever you use arrays in a comparison, the array is converted to its string representation, which is simply a comma delimited list of its elements. JavaScript is not comparing each element of the array individually.
So in your example, you are concatenating
a.namewitha.companyandb.namewithb.companyand compare this concatenation:What is the catch?
You will have problems though if any of these values is a number (not a string), since the lexicographical order of numbers is different than their numerical order.
For example:
You end up comparing
'a,100'against'a,11', and since0comes before1, the first string is smaller than second one.The bottom line is: If you know that you are only dealing with string values, you are probably fine, though the implicit concatenation can be difficult to comprehend.
Once you have mixed data types, you really should compare the values individually.