0

I am creating a simple shuffle/unshuffle function in an Angular app I'm building. The idea is there is a single button, on click it will either clone the array, shuffle the array, then return a shuffled order of the array, or if the array has already been shuffled, it will return the clone of the original array so that the user can revert back to the original order.

The issue I am having is I cannot figure out how to return the original order clone back to the view.

Here is a Fiddle: http://jsfiddle.net/nf6j1qvz/

Here is some function code:

$scope.shuffleThis = function(array) {
    if(!$scope.isShuffled){
        $scope.isShuffled = true;
        $scope.unshuffled = array.slice(0);
        var m = array.length, t, i;
        // While there remain elements to shuffle
        while (m) {
            // Pick a remaining element…
            i = Math.floor(Math.random() * m--);
            // And swap it with the current element.
            t = array[m];
            array[m] = array[i];
            array[i] = t;
        }
        return array;
    }else{
        console.log('unshuffling');
        $scope.isShuffled = false;
        array = $scope.unshuffled;
        return array;
    }
}
1
  • Your return is not being used anywhere, angular is just picking up on the changes within the original array itself Commented Mar 2, 2015 at 22:41

2 Answers 2

1

You can change your ng-click as follows

 <button ng-click="array = shuffleThis(array)">

And you're done!

Plunkr:

http://jsfiddle.net/grmqxx9e/

Sign up to request clarification or add additional context in comments.

Comments

1

Use angular.copy instead to clone the array. It's a deep copy and has always worked for me where the method you are using is not reliable.

https://docs.angularjs.org/api/ng/function/angular.copy

var originalArray = [];
angular.copy(array, originalArray);
// Continue doing your stuffs

But also, you are calling a function that has a return, so you are not setting that variable properly.

You could either change your ng-click to

ng-click='array = shuffleThis(array)'

Or instead of

return array

in your function, do

$scope.array = array;

I would do the second method personally.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.