Last active
May 30, 2018 10:12
-
-
Save zubayerahamed/fcc86d53658e530e5a406f5c1929568b to your computer and use it in GitHub Desktop.
How to sort array of object in javascript (Dynamic Sort)
This file contains 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
let a = [{aa:"1",xx:true},{aa:"10",xx:false},{aa:"2",xx:true},{aa:"11",xx:false},{aa:"3",xx:true},{aa:"12",xx:false},{aa:"4",xx:true},{aa:"13",xx:false},{aa:"5",xx:true},{aa:"14",xx:false},{aa:"6",xx:true},{aa:"15",xx:false},{aa:"7",xx:true},{aa:"16",xx:false},{aa:"8",xx:true},{aa:"17",xx:false},{aa:"9",xx:true},{aa:"18",xx:false}]; | |
//a.sort(function(a,b){return a.xx-b.xx}); | |
a.sort(function (x, y) { | |
// true values first | |
return (x.xx === y.xx) ? 0 : x ? -1 : 1; | |
// false values first | |
// return (x === y)? 0 : x? 1 : -1; | |
}); | |
return JSON.stringify(a); |
This file contains 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 dynamicSort = function(property) { | |
var sortOrder = 1; | |
if (property[0] === "-") { | |
sortOrder = -1; | |
property = property.substr(1); | |
} | |
return function(a, b) { | |
var result = (a[property] < b[property]) ? -1 | |
: (a[property] > b[property]) ? 1 : 0; | |
return result * sortOrder; | |
} | |
} | |
var People = [ | |
{Name: "Name", Surname: "Surname"}, | |
{Name:"AAA", Surname:"ZZZ"}, | |
{Name: "Name", Surname: "AAA"} | |
]; | |
People.sort(dynamicSort("Name")); | |
People.sort(dynamicSort("Surname")); | |
People.sort(dynamicSort("-Surname")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment