数组按多个值排序
array.sort by more than one value
我有一个数组变量,由对象填充。我需要按数组[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
。
相关文章:
- JavaScript数组排序(函数)用于对表行进行排序,而不是排序
- 在数组的 2/3 上调用自身的排序算法
- 数组值的排序以匹配另一个数组ES6
- 按不同项目对对象数组进行排序
- 根据Javascript中的字符串值对数组的数组进行排序
- 在不同的javascript数组中对json响应进行排序
- 对对象数组中的数组进行排序
- 按特定键对对象数组进行排序
- 使用jquery根据数组对表行进行排序
- 尝试对对象数组进行排序但拼接不是一个函数
- 对javascript中某些键的对象数组进行排序
- Javascript按数字顺序排序()数组
- Javascript排序索引链接数组
- 在jquery中对时间数组进行排序
- 如何在具有相同 ID 的 Javascript 中按排序函数对关联数组进行排序
- Javascript中的多维数组排序索引问题
- 如何在mongodb中根据数组内容的差异进行排序
- 在Javascript中对具有特定异常的对象数组进行排序
- 数组数据排序类似mysql查询
- 在小于O(n)时间内找到(排序)数组中的重复元素