【问题标题】:I need help simplifying code that compares various properties of objects我需要帮助简化比较对象的各种属性的代码
【发布时间】:2021-08-06 03:08:06
【问题描述】:

我强烈怀疑我的代码过于笨拙,可以以更简洁和有效的方式编写。目的是比较一组对象(代表玩家)以找到具有最高多数得分属性的玩家。如果有多个玩家共享相同的高分,则将共同获胜者的阵营与地图(priorityMap)进行比较,以确定谁获胜。

players = [
  {
    majorityScore: 4,
    faction: 'AR'
  },
  {
    majorityScore: 8,
    faction: 'MOU'
  },
  {
    majorityScore: 2,
    faction: 'MOB'
  },
  {
    majorityScore: 8,
    faction: 'I'
  }
];

const priorityMap = {
  'MOB': 1,
  'I': 2,
  'MOU': 3,
  'AR': 4,
  'S' : 0
}

let winner;
let highScore = -1;
let duplicates = [];
for(let i = 0; i < players.length; i++){
  if(players[i].majorityScore > highScore){
    highScore = players[i].majorityScore;
    winner = players[i]
    duplicates = [winner];
  } else if (players[i].majorityScore === highScore){
    duplicates.push(players[i]);
  };
}
if(duplicates.length > 1){
  let highFactionScore = duplicates.reduce((a,v) => {
    if(priorityMap[v.faction] > a){
      a = priorityMap[v.faction];
    }
    return a;
  }, 0);
  let winningFaction = Object.keys(priorityMap).find((k) => {
    return priorityMap[k] === highFactionScore;
  });
  winner = duplicates.filter((v) => {
    return v.faction === winningFaction
  })
}

【问题讨论】:

    标签: javascript arrays javascript-objects


    【解决方案1】:

    由于您要将一组对象归约为一个对象,因此可以在此处使用 reduce 函数:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

    您可以在比较具有相同多数分数的玩家时检查派系,而不是在获得最高分的玩家后检查派系。

    let winner = players.reduce((accum, currVal) => {
        if (accum.majorityScore < currVal.majorityScore) {
            return currVal;
        } else if (accum.majorityScore > currVal.majorityScore) {
            return accum;
        } else {
            return priorityMap[accum.faction] > priorityMap[currVal.faction] ? accum : currVal
        }
    });
    

    【讨论】:

      【解决方案2】:

      这是一个稍微短一些的方法。它使用一个临时对象来维护一个字典,其中分数是键。当我们迭代时,我们将priorityMap[faction] 的值添加到 score 属性中,并且仅当值大于存储的值时才更改它。

      const players=[{majorityScore:4,faction:"AR"},{majorityScore:8,faction:"MOU"},{majorityScore:8,faction:"MOU12"},{majorityScore:8,faction:"MOU20"},{majorityScore:2,faction:"MOB"},{majorityScore:2,faction:"MOB2"},{majorityScore:8,faction:"I"}],priorityMap={MOB:1,I:2,MOU:3,MOB2:4,AR:4,S:0,MOU12:21,MOU20:22};
      
      function getGroups(arr) {
      
        // Create the temp object
        // We'll be using the scores as keys, and using
        // the value in priorityMap as the value
        // As we iterate we check the new priorityMap value
        // against the old one
        const temp = {};
      
        // Iterate over the players array
        return arr.reduce((acc, c) => {
          const { majorityScore: score, faction } = c;
      
          // If the accumulator object doesn't have a key that
          // matches the score, add a new object
          acc[score] = (acc[score] || { majorityScore: score, faction });
      
          // If the new value of priorityMap[faction] is
          // greater than the one stored in temp
          // update the faction in the accumulator for that score
          if (priorityMap[faction] > temp[score]) {
            acc[score].faction = faction;
          }
      
          // Update the temp object with the
          // priorityMap[faction] value
          temp[score] = priorityMap[faction];
      
          // Return the accumulator for the next iteration
          return acc;
        }, {});
      }
      
      console.log(getGroups(players));

      【讨论】:

        猜你喜欢
        • 2011-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-02
        • 1970-01-01
        • 2012-03-16
        • 1970-01-01
        相关资源
        最近更新 更多