0
\$\begingroup\$

I have an array called list bound to the current application scope $scope that is a user order-able list of UI components. When clicking the up / down arrays these functions are responsible for moving the element by re-inserting it in the correct place.

$scope.moveUp = function(index)
{
    if (index === 0) {
        return;
    }
    $scope.list.splice(index - 1, 0, $scope.list.splice(index, 1)[0]);
};

$scope.moveDown = function(index)
{
    if (index === $scope.list.length - 1) {
        return;
    }
    $scope.list.splice(index + 1, 0, $scope.list.splice(index, 1)[0]);
};
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

What you are doing isn't very efficient. First you remove the element from the array, and to close the gap, every single element after it has to move position. Then you insert the element again, and to make room for it, every single element after it has to move position again, back to where they started.1

What you are doing is simply swapping to elements in the array. There is no need to do any array manipulation or touch any of the other elements.

$scope.moveUp = function(index)
{
    if (index === 0) {
        return;
    }
    [$scope.list[index], $scope.list[index-1]] = [$scope.list[index-1], $scope.list[index]];
};

$scope.moveDown = function(index)
{
    if (index === $scope.list.length - 1) {
        return;
    }
    [$scope.list[index], $scope.list[index+1]] = [$scope.list[index+1], $scope.list[index]];
};

I'm using destructuring to swap the values. It's basically a way to assign multiple values at the same time without needing a temporary variable.

1 That's how it works in theory at least. It will depend on the internal working of the JavaScript engine, and whether it has been optimized for this kind of task.

\$\endgroup\$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.