[removed] move objects from one array to another: Best approach?

后端 未结 7 678
臣服心动
臣服心动 2021-01-04 01:38

I have two arrays, called \'objects\' and \'appliedObjects\'. I\'m trying to come up with an elegant way in Javascript and/or Angular to move objects from one array to anot

7条回答
  •  一向
    一向 (楼主)
    2021-01-04 02:19

    function moveElements(source, target, moveCheck) {
        for (var i = 0; i < source.length; i++) {
            var element = source[i];
            if (moveCheck(element)) {
                source.splice(i, 1);
                target.push(element);
                i--;
            }
        } 
    }
    
    function selectionMoveCheck(element) {
       if (element.selected) {
           element.selected = false;
           return true;
       }
    }
    
    $scope.remove = function () {
        moveElements($scope.appliedObjects, $scope.objects, selectionMoveCheck);
    }
    
    $scope.add = function () {
        moveElements($scope.objects, $scope.appliedObjects, selectionMoveCheck);
    }
    

提交回复
热议问题