Skip to content

Instantly share code, notes, and snippets.

@schmidt1024
Created March 28, 2017 14:21
Show Gist options
  • Save schmidt1024/f73ed60c1e8571186d5673acf1917f5b to your computer and use it in GitHub Desktop.
Save schmidt1024/f73ed60c1e8571186d5673acf1917f5b to your computer and use it in GitHub Desktop.
typescript/javascript sort array of objects by attribute second level
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