0

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();

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.