如何在不创建新数组时从对象数组中筛选符合多条件的最优士兵?
Alright, let's figure out how to solve this without creating a new array—super straightforward once you break it down. Here's a step-by-step approach with code to match your soldier data:
核心思路
We don't need to copy values into a new array at all. Instead, we'll just iterate through the original soldiers array directly, keeping track of the best candidate as we go:
- Start with a variable to hold the current best soldier (initially
null). - Loop through each soldier in the original array.
- First, skip any soldier that doesn't meet your baseline condition (like
combat >= 60). - Compare the current soldier to the stored "best" one using your multi-attribute rules, updating the best soldier whenever we find a better match.
代码实现 (JavaScript example)
Since your data is structured as an array of objects, here's a concrete implementation using your exact soldier data:
// Your original soldier array const soldiers = [ {name: 'John', shooting: 95, combat: 50, tactic: 88}, {name: 'Arnold', shooting: 97, combat: 72, tactic: 68}, {name: 'William', shooting: 87, combat: 86, tactic: 97} ]; // Variable to track our best soldier (no new array needed!) let bestSoldier = null; // Iterate directly over the original array for (const soldier of soldiers) { // Step 1: Skip anyone who fails the baseline combat requirement if (soldier.combat < 60) { continue; } // If we haven't picked a best soldier yet, set this one if (!bestSoldier) { bestSoldier = soldier; continue; } // Step 2: Multi-attribute comparison (customize these rules to fit your needs!) // Here we'll use priority: tactic > shooting > combat if (soldier.tactic > bestSoldier.tactic) { bestSoldier = soldier; } else if (soldier.tactic === bestSoldier.tactic) { // If tactics are tied, check shooting if (soldier.shooting > bestSoldier.shooting) { bestSoldier = soldier; } else if (soldier.shooting === bestSoldier.shooting) { // If shooting is tied, check combat if (soldier.combat > bestSoldier.combat) { bestSoldier = soldier; } } } } // Get the result const result = bestSoldier ? bestSoldier.name : "No soldiers meet the criteria"; console.log(result); // Outputs: William
灵活调整规则
You can tweak the comparison logic to fit any multi-attribute criteria you need:
- If your rule is "combat >=60 AND shooting + tactic >= 160", add that check before comparing attributes.
- If you need to return multiple top soldiers (e.g., two with the same highest tactic score), you can switch
bestSoldierto a small array (though this is technically a new array, it's minimal and still avoids copying the entire soldier dataset). - Adjust the priority order (e.g., make
combatthe top priority instead oftactic) by reordering the comparison checks.
内容的提问来源于stack exchange,提问作者Vontar
相关产品推荐
相关产品推荐

