簡體   English   中英

如何對對象數組進行排序和切片

[英]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);
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM