Skip to content

Instantly share code, notes, and snippets.

@santhosh17s
Created February 27, 2018 09:54
Show Gist options
  • Save santhosh17s/0f58bc97e19c885b1e08c938fded9bad to your computer and use it in GitHub Desktop.
Save santhosh17s/0f58bc97e19c885b1e08c938fded9bad to your computer and use it in GitHub Desktop.
Sort by Two Fields in JS
var obj = [
{ "name":'a', "count1": 1, "count2": 9 },
{ "name":'b', "count1": 10, "count2": 4 },
{ "name":'c', "count1": 21, "count2": 93 },
{ "name":'d', "count1": 10, "count2": 10 },
{ "name":'e', "count1": 10, "count2": 2 },
{ "name":'f', "count1": 5, "count2": 9 },
];
obj.sort(function(a, b) {
return a.count1 - b.count1 || a.count2 - b.count2;
});
console.log(obj);
/*[
[object Object] { count1: 1, count2: 9, name: "a" },
[object Object] { count1: 5, count2: 9, name: "f" },
[object Object] { count1: 10, count2: 2, name: "d" },
[object Object] { count1: 10, count2: 4, name: "b" },
[object Object] { count1: 10, count2: 10, name: "e" },
[object Object] { count1: 21, count2: 93, name: "c" }] */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment