0

I've got an array populated with objects. These objects start with two values: sort1 and sort2.

var arr_obj = [
    {
        sort1:'3000',
        sort2:'200',
        value:'Value1'
    },
     {
        sort1:'4000',
        sort2:'100',
        value:'Value2'
    },
     {
        sort1:'6000',
        sort2:'200',
        value:'Value3'
    },
     {
        sort1:'6000',
        sort2:'100',
        value:'Value4'
    },
     {
        sort1:'2000',
        sort2:'500',
        value:'Value5'
    }
];

How do I go about sorting the objects based on the values of sort1 and sort2. Sort1 is dominant and if two values have the same sort1 value then the sort function should look at sort2 to determine which one comes first.

So for my example array the output should become.

[
    {
        sort1:'2000',
        sort2:'500',
        value:'Value5'
    },
    {
        sort1:'3000',
        sort2:'200',
        value:'Value1'
    },
     {
        sort1:'4000',
        sort2:'100',
        value:'Value2'
    },
    {
        sort1:'6000',
        sort2:'100',
        value:'Value4'
    },
     {
        sort1:'6000',
        sort2:'200',
        value:'Value3'
    }     
];

I tried just using a simple sort() on the array, but this probably looks at the index not the first values. Does anyone know how to get the requested output?

FIDDLE

timo
  • 2,119
  • 1
  • 24
  • 40

2 Answers2

2

You can set a compare function into the sort.

arr_obj.sort(function(a,b) {
  if (a.sort1 === b.sort1) {
    return a.sort2 - b.sort2;
  }
  return a.sort1 - b.sort1;
});
sbaglieri
  • 319
  • 2
  • 10
0

Try this:-

arr_obj.sort(function(prev,next){
  if(prev.sort1 != next.sort1){
    return prev.sort1 > next.sort1;
  }else{
   return prev.sort2 > next.sort2;
  }
});
Indranil Mondal
  • 2,799
  • 3
  • 25
  • 40