whyAto8 whyAto8 - 1 year ago 90
Javascript Question

javascript - sort by multiple criteria - first by another array and then by another property inside

I have an array of objects as below and need to sort it in such fashion that items with c comes first, then y , then s. And in that too, for e.g. in c, it should be sorted by counter i.e. c- counter 1, c- counter 2.

var data = [ { age:7, counter: 1, code: 'c'},
{ age:5, counter: 2, code: 'c'},
{ age:4, counter: 3, code: 'c'},
{ age:19, counter: 2, code: 'y'},
{ age:22, counter: 1, code: 'y'},
{ age:57, counter: 1, code: 's'},
{ age:80, counter: 2, code: 's'}

Upon looking on SO, I was able to sort by c, y, s as below, but could not do another sort for counter inside. How can I do that.

var order =[c,y,s];
return order.indexOf(a.code) < order.indexOf(b.code) ? -1:1;

Answer Source

You need to specify array as

var order =['c', 'y', 's'];

otherwise c, y and s needs to be variables.

Also, you need to compare the counter variables as well if codes are equal

   if ( a.code == b.code )
        return a.counter - b.counter;
       return order.indexOf(a.code) - order.indexOf(b.code);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download