Javascript: move objects from one array to another: Best approach?
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);}
When a construct does too much automatically (like forEach, or even a for-loop, in this case), use a more primitive construct that allows you to say what should happen clearly, without need to work around the construct. Using a while loop, you can express what needs to happen without resorting to backing up or otherwise applying workarounds:
function moveSelected(src, dest) { var i = 0; while ( i < src.length ) { var item = src[i]; if (item.selected) { src.splice(i,1); dest.push(item); } else i++; }}
You are altering the array while iterating on it, you will always miss some elements.
One way of doing it would be to use a third array to store the references of the objects that need to be removed from the array:
// "$scope.add" casevar objectsToRemove = [];$scope.objects.forEach(function (value) { if (value.selected) { value.selected = false; $scope.appliedObjects.push(value); objectsToRemove.push(value); }});objectsToRemove.forEach(function (value) { $scope.objects.splice($scope.objects.indexOf(value), 1);});