2015-01-13 5 views
0

У меня есть переменная массива, заполненная объектами. Мне нужно отсортировать массив по массиву [i] .target; затем вторичный по массиву [i] .weaponPriority Я могу сортировать массив по одному значению, но, к сожалению, я не могу понять, как я мог его доработать.array.sort более чем на одно значение

Прошу совета.

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

ответ

5

Вы могли бы попробовать что-то вроде этого:

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

Вы пройдете эту функцию в sort.

Смежные вопросы