简体   繁体   English

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

[英]How to sort and slice an array of objects

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". 我已经能够获取该数组并遍历整个数组以获取在#1孔上发生的所有镜头,然后根据“ shot_number”对它们进行重新排列。 I now need to do this for every hole and to create an array for each hole (ex: holeArray1, holeArray2). 现在,我需要对每个孔进行此操作,并为每个孔创建一个数组(例如: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. 我尝试了多种解决方案来增加x,但是如果这样做,我最终会丢失某些孔上发生的一些击球。

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? 我如何重构此函数以为每个孔创建此数组,而不仅仅是复制和粘贴代码并自己更改变量x? 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);
};

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM