0

I have an array of shots. I have been able to take that array and loop through it to get all shots that occurred on hole #1 and then rearrange them in order based on "shot_number". I now need to do this for every hole and to create an array for each hole (ex: holeArray1, holeArray2). I have attempted a number of solutions to increment x but if I do I end up missing some shots that occurred on certain holes.

How can I refactor this function to create this array for every hole without just copying and pasting the code and changing the variable x myself? Thank you for your help. I know I should be able to figure this one out but am struggling.

  $scope.createHoleShotsArrays = function () {
    var i = 0;
    var x = 1;
    var holeArray = [];
    var len = $scope.shots.length;
    for (; i < len; i++) {
        if ($scope.shots[i].attributes.hole == x) {
            holeArray.push($scope.shots[i]);
            holeArray.sort(function (a, b) {
                if (a.attributes.shot_number > b.attributes.shot_number) {
                    return 1;
                }
                if (a.attributes.shot_number < b.attributes.shot_number) {
                    return -1;
                }
                // a must be equal to b
                return 0;
            });
        }
    }
    console.log(holeArray);
};
1
  • 1
    Sorting an array inside a loop is definitely not what you want to do. Push the items you want on the array and then sort once outside the loop. Commented Aug 3, 2015 at 1:26

1 Answer 1

1

Push the items you want into arrays, and sort them once. I don't have cases to test the code. You may modified it a little if something goes wrong.

$scope.createHoleShotsArrays = function() {
  var holeArrays = [];
  $scope.shots.forEach(function(shot) {
    if (holeArrays.length < shot.attributes.hole) {
      holeArrays[shot.attributes.hole - 1] = [];
    }
    holeArrays[shot.attributes.hole - 1].push(shot);
  });

  holeArrays.forEach(function(arr) {
    arr.sort(function(a, b) {
      return a.attributes.shot_number - b.attributes.shot_number;
    });
  });

  console.log(holeArrays);
};
Sign up to request clarification or add additional context in comments.

1 Comment

much more elegant than anything I would have come up with.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.