Shuffling an array and returning it using Javascript/Angular

I have been working on implementing a shuffle/unshuffle feature in my Angular application. The concept is simple - there's a single button that, when clicked, will either shuffle an array and return the shuffled order, or if the array has already been shuffled, it will revert back to the original order by returning a clone of the original array.

My problem lies in figuring out how to display the original order clone in the view.

For reference, here is a Fiddle where you can see the code in action: http://jsfiddle.net/nf6j1qvz/

Below is the function code for this functionality:

$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;
    }
}

Answer №1

To modify the function triggered by ng-click, simply make the following adjustment:

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

That's all there is to it!

Check out the demonstration on Plnkr:

http://jsfiddle.net/grmqxx9e/

Answer №2

To make a clone of the array, consider using angular.copy instead. It performs a deep copy and has been more reliable in my experience compared to other methods.

Here is the link for more information: https://docs.angularjs.org/api/ng/function/angular.copy

var newArray = [];
angular.copy(arrayToClone, newArray);
// Continue with your tasks

Additionally, since you are calling a function that returns a value, ensure you are assigning it correctly.

You can update your ng-click to:

ng-click='arrayToClone = shuffleArray(arrayToClone)'

Instead of returning the array directly in your function, you can do:

$scope.arrayToClone = arrayToClone;

In my opinion, I would go with the second approach.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can someone explain how to use JavaScript to make table data fill the entire row in a table?

After clicking the button, the layout of the table changes. I want to keep the original table layout even after the JavaScript function runs. I am still learning about JavaScript. function toggle(button) { if(document.getElementById("1").value=="Show ...

methods for deleting an object from a AngularJS $scope variable

Looking for assistance in removing a single object from the $scope.Profile.address object. Below is the code and image for reference: <tr ng-repeat="x in Profile.addresses"> <td><input type="text" class="form-control" id="inputDefault" ...

Display a q-table inside a nested row q-table component

In order to display lists within items in another list, such as a list of chapters with their titles, I am trying to achieve this using q-tables instead of q-list. Although it is usually straightforward with q-list, I am facing some challenges while worki ...

Tinymce editor does not display icons as expected

I am attempting to create a custom styled list that is editable with tinymce. The list-items are using Material-Check-Icons as bullet-points, which are added as css-pseudo-elements ::before. This setup works well, but when I integrate tinymce (v5) into the ...

Incorporating JavaScript and CSS files into a content page of a master page in ASP.NET: Steps to follow

I am facing an issue with adding javascript files and css to a content page of a master page in asp.net. I attempted to include a datetime picker on my ContentPage, but it only works on the masterpage. When I try to add the same code to my contentpage, i ...

Is the purpose of express.json() to identify the Request Object as a JSON Object?

app.js const express = require('express'); const cookieParser = require('cookie-parser'); const session = require('express-session'); const helloRouter = require('./routes/hello'); const app = express(); app.set(& ...

Is there a way I can detect a browser timeout and display a custom error message?

My webpage in classic asp contains a link to a local IP address, shown below: <a href="http://192.168.1.89">Link</a> When the local IP address is not available, the web browser eventually times out and shows its own error message. I ...

Shift attention to the subsequent division after a correct radio option or text input has been submitted

I need to enhance the user experience on my form. When a user interacts with specific elements like hitting enter in a text input or clicking a radio button, I want to automatically focus on the next "formItem" division. My form structure is organized as ...

Transform a checkbox input into two distinct buttons

I am trying to change the input checkbox that toggles between light and dark mode into two separate buttons. How can I achieve this functionality? Check out the demo here: https://jsfiddle.net/ot1ecnxz/1 Here is the HTML code: <input type="checkb ...

What steps can be taken to address the build problem with Angular version 13?

Encountering a problem while working with Angular 13: https://i.sstatic.net/CbAUhh6r.png Attempting to build using ng build --configuration=test, however facing errors as mentioned above. Interestingly, if I remove the reference to bootstrap.min.css in t ...

Oops! Looks like there's an unexpected error with the module 'AppRoutingModule' that was declared in the 'AppModule'. Make sure to add a @Pipe/@Directive/@Component annotation

I am trying to create a ticket, but I encountered an error. I am currently stuck in this situation and receiving the following error message: Uncaught Error: Unexpected module 'AppRoutingModule' declared by the module 'AppModule'. Plea ...

How can I convert a series of numerical values into a numpy array?

Is there an alternate method to convert '1 2 3' into a numpy array [1, 2, 3] besides using np.fromstring()? Maybe through np.array() instead? Appreciate any insights. Thanks! I attempted the following: x = '1 2 3' x = np.fromstring(x, ...

The infinite scrolling feature encounters issues when scrolling downwards

My infinite scroll code is causing a problem - it only works when scrolling up, not down. Can someone help me fix this issue? <script type="text/javascript"> $(document).ready(function(){ $(window).scroll(function(){ var lastID = $(&apos ...

Personalized directive for HTTP validation, display dialog box upon detection of incomplete match

Looking to validate input against a server-side REST API and provide options for selection if invalid while typing. Already implemented in jQuery, now looking to implement in AngularJS. Would it be better as a custom directive or functions in the controll ...

Animating content with Jquery Waypoints for a seamless and elegant user experience

Currently tackling a project that requires some jQuery functions beyond my current skill set. Hoping to find some solutions here! The project in question is a one page scroll site, with existing jquery and waypoints functions implemented. Check out the c ...

Filter error - Unable to retrieve property 'toLowerCase' from null value

When filtering the input against the cached query result, I convert both the user input value and database values to lowercase for comparison. result = this.cachedResults.filter(f => f.prj.toLowerCase().indexOf((this.sV).toLowerCase()) !== -1); This ...

Strategies for tracking distinct property values in Firestore

Is it possible to count the occurrences of unique values in Firestore? For instance, if there are 1000 documents with dates and only 50 different dates repeated, how can I get a list of each date along with its frequency? Context: These documents represe ...

Issue with ExpressJS Regex not correctly matching a path

I'm currently struggling with a simple regex that is supposed to match words consisting of letters (0-5) only, but for some reason it's not working as expected. Can anyone help me figure out the correct expression and how to implement it in Expre ...

Encountering a 404 error when trying to reload the page?

My React Router is functioning properly in the development environment. Here's what I implemented in Webpack Dev Server: historyApiFallback: { index: 'index.html', } Now, when transitioning to production mode, I wanted to replicate the ...

Can you explain the purpose of using double colons before an expression variable in AngularJS?

Can you explain the use of double colons :: preceding an expression variable in AngularJS? Additionally, how does {{ firstName }} differ from {{ ::firstName }}? ...