在$ .each循环中对数组元素进行排序

时间:2019-09-04 05:36:48

标签: javascript

我有这个代码。 :

$.getJson('api/players_.json', function(players){
// ... some logic code stuff to generate a custom parent object
// with 20 teams of 11 players
$.each(chosenSetupPerTeam, function(i){
     console.log(chosenSetupPerTeam[i]);
     $.each(chosenSetupPerTeam[i], function(n){

       console.log(chosenSetupPerTeam[i][n].player_surname +' '+chosenSetupPerTeam[i][n].role_name +' '+chosenSetupPerTeam[i][n].team_name);

     });
});

我正在$.getJSON调用中实现数组迭代,以将某些元素附加到DOM。

它工作正常,但是我需要使用criterio对迭代结果进行排序。 这是控制台日志,我想按角色对玩家进行排序 例如:Portiere, Difensore, Centrocampista, Attaccante。 我还想问一个嵌套对象示例:array(20) that contains array(11),是否是一种更好的迭代方法?

Extension Started!
team.min.js:1 Array(11)
team.min.js:1 Mazzitelli Centrocampista Sassuolo
team.min.js:1 Gravillon Difensore Sassuolo
team.min.js:1 Pegolo Portiere Sassuolo
team.min.js:1 Traoré Centrocampista Sassuolo
team.min.js:1 Matri Attaccante Sassuolo
team.min.js:1 Babacar Attaccante Sassuolo
team.min.js:1 Muldur Difensore Sassuolo
team.min.js:1 Goldaniga Difensore Sassuolo
team.min.js:1 Peluso Difensore Sassuolo
team.min.js:1 Magnanelli Centrocampista Sassuolo
team.min.js:1 Obiang Centrocampista Sassuolo

有人可以引导我吗?

1 个答案:

答案 0 :(得分:1)

您可以在此处使用Array#sort方法,通过此比较器回调,通过每个团队成员拥有的role_name字段对任何给定团队的每个成员进行排序:

function (memberA, memberB) {
    /* If memberA role name alphabetically before memberB role_name
    then order memberA before memberB */
    return memberA.role_name < memberB.role_name ? -1 : 1;
}

可以将其合并到您的代码中,如下所示:

/* Use of forEach here is optional */
chosenSetupPerTeam.forEach(function(team) {

  /* Call sort() on the team array, and use comparator above to sort
     team members based based on the role name */
  const teamOrderedByRole = team.sort(function (memberA, memberB) {
      return memberA.role_name < memberB.role_name ? -1 : 1;
  });

  console.log(teamOrderedByRole);
});