Christian F
Christian F

Reputation: 259

array.sort by more than one value

I have an array variable, filled by objects. I need to sort this array primary by array[i].target; then secondary by array[i].weaponPriority I can sort an array by one value, but unfortunally i cant grasp how i could refine it further.

Please advice.

var ships = []

function Ship(name, target, priority){
this.name = name;
this.target = target;  
this.id = ships.length;
this.weaponPriority = priority;
}

var ship = new Ship("Alpha", 10, 3);
ships.push(ship);
var ship = new Ship("Beta", 10, 1);
ships.push(ship);
var ship = new Ship("Gamma", 10, 3);
ships.push(ship);
var ship = new Ship("Delta", 15, 2);
ships.push(ship);


function log(){
for (var i = 0; i < ships.length; i++){
  var shippy = ships[i];
  console.log(shippy.name + " ---, targetID: " + shippy.target + ", weaponPrio: " + shippy.weaponPriority);              
}


ships .sort(function(obj1, obj2){
...
});

log();

Upvotes: 0

Views: 69

Answers (1)

Christos
Christos

Reputation: 53958

You could try something like this:

function( obj1, obj2 ){
    // We check if the target values are different.
    // If they are we will sort based on target
    if( obj1.target !== obj2.target )
         return obj1.target-obj2.target
    else // The target values are the same. So we sort based on weaponPriority
        return obj1.weaponPriority-obj2.weaponPriority; 
}

You will pass this function to the sort.

Upvotes: 5

Related Questions