Created
November 13, 2014 00:38
-
-
Save gal-at-aljazeera/810c6e7631a71e06da16 to your computer and use it in GitHub Desktop.
Javascript sort by 2 attributes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ary = [{a:1, b:2, c:3}, {a:3, b:5, c:3}, {a:2, b:3, c:3}, {a:2, b:2, c:3}, {a:3, b:4, c:3}, {a:3, b:3, c:3} ]; | |
JSON.stringify(ary.sort()); | |
"[{"a":1,"b":2,"c":3},{"a":3,"b":5,"c":3},{"a":2,"b":3,"c":3},{"a":2,"b":2,"c":3},{"a":3,"b":4,"c":3},{"a":3,"b":3,"c":3}]" | |
JSON.stringify(ary.sort(function(x,y){return x['a'] - y['a']})) | |
"[{"a":1,"b":2,"c":3},{"a":2,"b":3,"c":3},{"a":2,"b":2,"c":3},{"a":3,"b":5,"c":3},{"a":3,"b":4,"c":3},{"a":3,"b":3,"c":3}]" | |
JSON.stringify(ary.sort(function(x,y){return [x['a'] - y['a'],x['b']-y['b']]})) | |
"[{"a":1,"b":2,"c":3},{"a":2,"b":3,"c":3},{"a":2,"b":2,"c":3},{"a":3,"b":5,"c":3},{"a":3,"b":4,"c":3},{"a":3,"b":3,"c":3}]" | |
JSON.stringify(ary.sort(function(x,y){return x['a'] - y['a'] || x['b']-y['b']})) | |
"[{"a":1,"b":2,"c":3},{"a":2,"b":2,"c":3},{"a":2,"b":3,"c":3},{"a":3,"b":3,"c":3},{"a":3,"b":4,"c":3},{"a":3,"b":5,"c":3}]" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment