Jayden
Jayden

Reputation: 283

Multilevel sorting for array of objects - javascript

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.

Upvotes: 0

Views: 85

Answers (3)

Saurabh Singh
Saurabh Singh

Reputation: 132

You can try something like this.

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'}];

array.sort((a, b) => {          
      if (a.city === b.city) {
        if(a.color === b.color) {
          return (a.objname).localeCompare(b.objname)
        }
        return (a.color).localeCompare(b.color)
      }
      return a.id - b.id
  }
);

console.log(array);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386680

You could take a dynamic approach by collecting the wanted keys and use Array#some with a short circuit for truthy values.

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' }],
    keys = ['id', 'color', 'objname'];

array.sort((a, b) => {
    var result;
    keys.some(k => result = (a[k] > b[k]) - (a[k] < b[k]));
    return result;
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Rajneesh
Rajneesh

Reputation: 5308

You can sort it with multiple OR conditions:

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'}];

var resultArray = array.sort((a,b)=>{
   return a.id-b.id || a.color.localeCompare(b.color) || a.objname.localeCompare(b.objname)
});

console.log(resultArray);

Upvotes: 1

Related Questions