0

I want to loop over every user in the same rank.

How would I do this with the following array so I can read it by doing array[rankId].forEach to loop over everyone with the same rank.

Array (Objects)

var array = [
    {
    user: '1xJs8A',
    rank: 1
  },
  {
    user: '1xJs8B',
    rank: 1
    },
  {
    user: '1xJs8C',
    rank: 2
    },
];

Edit: I want to be able to loop over the ranks as well, so I would need some sort of array as the following,

rankId:[
 { .. user data .. ] 
]
OrpheuZ
  • 37
  • 5

2 Answers2

0

Here is a simple way to do it. Note the different use of for ... in ... and for ... of ....

var array = [{
    user: '1xJs8A',
    rank: 1
  },
  {
    user: '1xJs8B',
    rank: 1
  },
  {
    user: '1xJs8C',
    rank: 2
  }];

var usersByRank = [];
for (item of array) {
  usersByRank[item.rank] = usersByRank[item.rank] || [];
  usersByRank[item.rank].push(item);
}

for (rank in usersByRank) {
  console.log(usersByRank[rank].length +
    " users with rank " + rank);
    
  for (item of usersByRank[rank]) {
    console.log(" > user " + item.user);
  }
}
raul.vila
  • 1,984
  • 1
  • 11
  • 24
-2
<script>
    window.onload=function(){
      var array = [
    {
    user: '1xJs8A',
    rank: 1
  },
  {
    user: '1xJs8B',
    rank: 1
    },
  {
    user: '1xJs8C',
    rank: 2
    },
];


for(var i=0; i<array.length;i++){
    if(array[i].rank==1){
        alert(array[i].user);
    }

}






        }

</script>
calmchess
  • 118
  • 8
  • How would I be able to loop over EVERYONE in a certain rank, but also be able to loop over the ranks in general. – OrpheuZ Apr 19 '18 at 21:55