如何对对象数组进行排序和切片

How to sort and slice an array of objects

我有一系列镜头。我已经能够获取该数组并循环遍历它以获取在第 1 洞发生的所有击球,然后根据 "shot_number" 按顺序重新排列它们。我现在需要为每个孔执行此操作并为每个孔创建一个数组(例如:holeArray1、holeArray2)。我已经尝试了多种解决方案来增加 x,但如果这样做,我最终会错过在某些洞上发生的一些击球。

我如何重构这个函数来为每个洞创建这个数组,而不仅仅是复制和粘贴代码并自己更改变量 x?谢谢您的帮助。我知道我应该能够解决这个问题,但我很挣扎。

  $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);
};

将你想要的项目压入数组,然后对它们进行一次排序。我没有案例来测试代码。有问题可以稍微修改一下。

$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);
};