Created
March 28, 2017 14:21
-
-
Save cod3cow/f73ed60c1e8571186d5673acf1917f5b to your computer and use it in GitHub Desktop.
typescript/javascript sort array of objects by attribute second level
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
sortArray(property, array) { | |
property = property.split('.'); | |
var l = property.length; | |
return array.sort( function(a, b) { | |
var i = 0; | |
while( i < l) { | |
a = a[property[i]]; | |
b = b[property[i]]; | |
i++; | |
} | |
return a < b ? -1 : 1; | |
}); | |
} | |
// this.array = [ | |
// { | |
// "id": 1, | |
// "name": "red pill", | |
// "price": { | |
// "item": 234, | |
// "tax": 34, | |
// "total": 268 | |
// } | |
// }, | |
// { | |
// "id": 2, | |
// "name": "blue pill", | |
// "price": { | |
// "item": 123, | |
// "tax": 12, | |
// "total": 135 | |
// } | |
// } | |
// ]; | |
// this.sortArray('price.total', this.array); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment