title: How to group the objects in array by their respective group number
body: <p>I've already sorted my array list and arrange it in sequence by their respective group number, but I need to group it, (<em>let's say by a leader and his/her member</em>). I want to have extra fields that if the object has no the same group number, It will be automatically tag as the leader, hence, if the object has the same group number, the first object in sequence will be tag as the leader and the other will be automatically tag as a member.</p>
  
  <blockquote>
    <p>THIS IS MY CODE FOR SORTING MY ARRAY LIST AND IT'S CONSOLE/OUTPUT.</p>
  </blockquote>
  
  <pre><code>$scope.sortedTopAgent = [];
  var c = 0;
  var sortTopAgentByGroup = function () {
  for (const [index, value] of accountArray.entries()) {
      for (const [index2, value2] of TeamArray.entries()) {
          if (value2.accountname == value) {
              c = c + 1;
  
              $scope.sortedTopAgent.push(value2); 
  
              $scope.sortedTopAgent.sort(function (a, b) {
                  return a.groupNo - b.groupNo;
              });
              console.log($scope.sortedTopAgent)
  
              //console &gt;&gt;
  
              [{
                  "name": "John",
                  "groupNo": 1
              },
              {
                  "name": "Chelsea",
                  "groupNo": 1
              },
              {
                  "name": "Mark",
                  "groupNo": 1
              },
              {
                  "name": "Peter",
                  "groupNo": 5
              },
              {
                  "name": "Arya",
                  "groupNo": 5
              },
              {
                  "name": "Robert",
                  "groupNo": 7
              },
              {
                  "name": "Mary",
                  "groupNo": 8
              }
          ]
              // end of console
          }
      }
  }
  </code></pre>
  
  <p>};</p>
  
  <p><strong>I want to have an array that will look like this:</strong></p>
  
  <pre><code>[{
      "name": "John",
      "groupNo": 1,
      "leaderNo": 1,
      "memberNo": ""
    },
    {
      "name": "Chelsea",
      "groupNo": 1,
      "leaderNo": "",
      "memberNo": 1
    },
    {
      "name": "Mark",
      "groupNo": 1,
      "leaderNo": "",
      "memberNo": 1
    },
    {
      "name": "Peter",
      "groupNo": 5,
      "leaderNo": 2,
      "memberNo": ""
    },
    {
      "name": "Arya",
      "groupNo": 5,
      "leaderNo": "",
      "memberNo": 2
    },
    {
      "name": "Robert",
      "groupNo": 7,
      "leaderNo": 3,
      "memberNo": ""
    },
    {
      "name": "Mary",
      "groupNo": 8,
      "leaderNo": 4,
      "memberNo": ""
    }
  ]
  </code></pre>