I'm trying to do multilevel ascending order sorting for below array of objects.
var array = [{id: 1, color: 'red', objname: 'tomato'},
{id: 1, color: 'orange', objname: 'pumpkin'},
{id: 2, color: 'red', objname: 'tomato' },
{id: 1, color: 'red', objname: 'cherry' },
{id: 1, color: 'orange', objname: 'sunset'}];
Expected result Array:
var resultArray =
[{id: 1, color: 'orange', objname: 'pumpkin'},
{id: 1, color: 'orange', objname: 'sunset'},
{id: 1, color: 'red', objname: 'cherry'},
{id: 1, color: 'red', objname: 'tomato'},
{id: 2, color: 'red', objname: 'tomato'}];
From above array of objects, first i want to sort 'id' level and color and finally objname. First level based on id I can able to do but with in that multilevel i dont have idea to sort. And this is how I'm sorting one level,
sortById(array, key) {
return array.sort(function(a, b) {
var x = a[key]; var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
With this i can ascending array of objects based on 'id'. Can any one help me, how can we perform multilevel sorting.