数组按多个值排序

array.sort by more than one value

本文关键字:排序 数组      更新时间:2023-09-26

我有一个数组变量,由对象填充。我需要按数组[i].target对这个数组进行主要排序;然后按数组[i]辅助。武器优先级我可以按一个值对数组进行排序,但不幸的是,我无法掌握如何进一步完善它。

请指教。

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

你可以尝试这样的事情:

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