根据多个对象的值对数组进行排序

时间:2019-12-30 16:18:29

标签: javascript arrays node.js

我有一个看起来像这样的数组:

  { username: 'usernameadw',
    rank: 'rookie',
    points: 891
  },
  { username: 'username662',
    rank: 'rookie',
    points: 999
  },
  { username: 'usernameabd8a',
    rank: 'knight',
    points: 2393
  },
  { username: 'usernamev88',
    rank: 'mage',
    points: 1673
  },
  { username: 'abcusername123',
    rank: 'mage',
    points: 1483
  }

我想知道如何将这些数组拆分为“ mageArray”,“ knightArray”,“ rookieArray”之类的数组,然后对每个数组按每个对象从最高到最低的点数进行排序?

到目前为止,我已经尝试使用此代码,但无法正常工作。我试图做的是从带有信息的大型数组中创建一个新对象,然后在等级名称匹配的情况下将其推到另一个数组中

var obj = new Object({
            username: usersRows[i].username,
            rank: usersRows[i].rank,
            points: usersRows[i].points
          });

if (usersRows[i].rank === 'mage') { mageArray.push(obj); }

2 个答案:

答案 0 :(得分:0)

尝试一下。

const usersRows = [{
    username: 'usernameadw',
    rank: 'rookie',
    points: 891
},
{
    username: 'username662',
    rank: 'rookie',
    points: 999
},
{
    username: 'usernameabd8a',
    rank: 'knight',
    points: 2393
},
{
    username: 'usernamev88',
    rank: 'mage',
    points: 1673
},
{
    username: 'abcusername123',
    rank: 'mage',
    points: 1483
}];


function makeSortMap(usersRows) {
    const sortMap = {};
    for(row of usersRows) {
        const key = row.rank;
        if(!sortMap[key]) {
            sortMap[key] = [];
        }

        sortMap[key].push(row);
    }

    for(r in sortMap) {
        sortMap[r].sort((a, b) => b.points - a.points);
    }

    return sortMap;
}

makeSortMap(usersRows);

排序参考:Sorting object property by values

答案 1 :(得分:0)

首先,使用以下命令将主数组分解为三个子数组:

var users = [{ username: 'usernameadw',
    rank: 'rookie',
    points: 891
  },
  { username: 'username662',
    rank: 'rookie',
    points: 999
  },
  { username: 'usernameabd8a',
    rank: 'knight',
    points: 2393
  },
  { username: 'usernamev88',
    rank: 'mage',
    points: 1673
  },
  { username: 'abcusername123',
    rank: 'mage',
    points: 1483
  }];

  var rookieArray = [];
  var knightArray = [];
  var mageArray = [];

  // split users into category arrays.
  for (i=0; i<users.length; i++) {

      if (users[i].rank === 'rookie') {
        rookieArray.push(users[i]);
      }

      if (users[i].rank === 'knight') {
        knightArray.push(users[i]);
      }

      if (users[i].rank === 'mage') {
        mageArray.push(users[i]);
        }      
  }

有了这些,我们只需要使用array.sort和一个比较函数对数值进行排序,如下所示:

// sort the rookies array
  rookieArray.sort(function(a, b) {
    return b.points - a.points;
  });

  knightArray.sort(function(a, b) {
    return b.points - a.points;
  });

  mageArray.sort(function(a, b) {
    return b.points - a.points;
  });

关于for循环的好参考书在这里:https://www.w3schools.com/js/js_loop_for.asp

关于array.sort的很好的参考资料在这里: https://www.w3schools.com/js/js_array_sort.asp