Achieving a truly random ordering in a Vue.js v-for loop

Looking to display a list in random order?

You can achieve this with a computed property:

<div id="app">

  <ul>
    <li v-for="item in shuffledList" >
      {{ item.text }}
    </li>
  </ul>

</div> 

<script>
      var vm = new Vue({


      el:'#app', 
      data:{
        items:[
          {text:'js',value:'one'},
          {text:'css',value:'two'}, 
          {text:'html',value:'three'}
        ]
      },

      computed: {
        shuffledList: function(){
          return this.items.sort(function(){return 0.5 - Math.random()});
        }
      }

    });
 </script>

If you have multiple lists and want to simplify the process, consider using methods or filters.

Attempting with methods:

<div id="app">

  <ul>
    <li v-for="item in shuffleList(items)" >
      {{ item.text }}
    </li>
  </ul>
   <ul>
     <li v-for="person in shuffleList(people)" >
     {{ person.text }}
    </li>
  </ul>


</div> 
<script>
      var vm = new Vue({


      el:'#app', 
      data:{
        items:[
          {text:'js',value:'one'},
          {text:'css',value:'two'}, 
          {text:'html',value:'three'}
        ],
        people:[
          {text:'mary',value:'one'},
          {text:'css',value:'two'}, 
          {text:'html',value:'three'}
        ]
      },

      methods: {
        shuffleList: function(list){
          return list.sort(function(){return 0.5 - Math.random()});
        }
      }

    });
 </script>

Answer №1

It appears that there are a few minor issues in your code. One of the errors is within your method: randomList. You are using this.rand when rand is actually passed as a parameter. To resolve this, you should simply access it via rand. Using this.rand will cause the code to look into vue instance data and result in the following error:

TypeError: this.rand is undefined[Learn More]

You can view a working example in this fiddle here

Code:

  methods: {
    randomList: function(rand){
      return rand.sort(function(){return 0.5 - Math.random()});
    }
  }

There seems to be a small typo here: el:'#vapp', => it should be changed to el:'#app',

Answer №2

In order to randomize the list (array) using javascript, it is important to note that this task is unrelated to Vue.js or v-for.

Your proposed method appears to be correct. It would be advisable to create a function like randomList(myList) to shuffle the array items and then directly utilize it within the v-for loop.

Instead of relying on a sort function with a true/false random return value, there exists a more efficient way to shuffle an array. You can refer to this link for guidance: How to randomize (shuffle) a JavaScript array?

If you examine the third response from that link which employs the sort() method to shuffle (similar to your initial attempt), you will discover that it is not the correct approach (as explained in the comments).

The optimal solution lies in the highest-rated answer, which you can integrate into your randomList() function. Below is a modified implementation (resembling the accepted solution from the reference link, but utilizing a separate array to preserve the original list):

methods: {
    randomList: function(array){
        var currentIndex = array.length;
        var temporaryValue;
        var randomIndex;
        var myRandomizedList;

        // Create a copy of the original array as myRandomizedList
        myRandomizedList = array.slice(0)

        // Shuffle elements within the myRandomizedList (shallow copy of original array)
        // Iterate through remaining elements...
        while (currentIndex !== 0) {

            // Select a random element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // Swap it with the current element.
            temporaryValue = myRandomizedList[currentIndex];
            myRandomizedList[currentIndex] = myRandomizedList[randomIndex];
            myRandomizedList[randomIndex] = temporaryValue;
        }

        // Return the newly shuffled array
        return myRandomizedList;
    }
}

Note: The code provided above has not been tested. It is simply extracted from the popular answer and adapted for use as a method within your Vue component after adjusting to randomize the duplicated array.

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

Trouble receiving JSON data from jQuery method

I am encountering difficulty in correctly capturing a JSON object within a function that is executed when the page loads. My goal is to capture this object so that I can later POST it to another page based on user action. This code is being run on Windows ...

MERN Stack deployment to Heroku: Remote rejected - unable to push changes to master branch (pre-receive hook declined)

Just a heads up: I've successfully deployed using this method around 3 times in the past, but now it seems to be failing. Could there have been an update with Heroku that's causing this issue? Not entirely sure... I'm attempting to push my ...

Tips for observing the return value of a function in JavaScript

When dealing with an object in a browser, each property has a getter and setter that can be overridden in order to monitor the attribute. But what about the return value of a function? In AngularJS, we can use 'ng-show' to control the visibility ...

Allowing certain routes to be processed by Groovy while others are managed by react-router v4

I'm currently dealing with a situation where the backend Groovy code contains controllers that render GSP (Groovy Server Pages), while for the frontend we're utilizing react-router v4 to manage routes. The issue that I am facing is that when defi ...

Adjusting the Connection header in a jQuery ajax request

I've been attempting to modify the Connection header using the code below, but so far, I haven't had any success jQuery.ajax({ url: URL, async: boolVariable, beforeSend: function(xhr) { xhr.setRequestHeader("Connection ...

Having trouble implementing a Font Awesome icon into a submit button programmatically

One way to use a font-awesome icon as button text in HTML is shown below: <button tabindex="4" type="submit" id="submit" class="btn btn-primary btn-lg disabled" onclick="sendemail(); return false;"><i class="fa fa-paper-plane" aria-hidden="true"& ...

Is purchasing a Twilio phone for sending SMS messages a good idea?

As part of my testing process, I have implemented this code for sending SMS messages. Everything is working fine so far, but I have a question regarding the necessity of purchasing a Twilio phone number to input into the "from" field. I intend to send real ...

Tips for creating responsive content within an iframe

I have inserted a player from a website that streams a channel using an iframe. While I have managed to make the iframe responsive, the video player inside the iframe does not adapt to changes in viewport size. Despite trying various solutions found online ...

Maintain functionality of React components even when they are not actively displayed

I have a unique page React app with different components. The App.js file controls which component to display based on server information. One specific component, the Stopwatch, is only rendered on two of the pages. Here's a snippet of code from my Ap ...

Is it necessary to have NodeJs in order to host a React app on a server?

I've been working on a .NET Core 2.2 project with React integration, As I'm nearing completion of the project, I have a query that has been on my mind. Do I need Node.js installed on the server for React to function properly? Thank you. ...

utilizing jQuery to iterate through JSON data with a random loop

Is there a way to modify this code to display only one image randomly selected from a JSON file that contains multiple images? Here is the code in question: $(document).ready(function() { $.getJSON('https://res.cloudinary.com/dkx20eme ...

Retrieving the slug from the parameters in the API response using this.$route

I am currently using vue-router to navigate from an 'index' page displaying records for a particular resource. I have set up a router-link to direct you to a separate page for each individual record. Although the route is functioning correctly, I ...

Using the .forEach method in JavaScript to convert JSON properties into HTML content

For my project, the JSON data is stored in the variable this.responseText: { 'nav': '<a href="">a</a><a href="">b</a>', 'content': '<div>tartalom</div>', ...

After upgrading Node, the import.meta.glob feature in vite/vue3 is no longer functioning properly

Recently, I encountered an issue in my code that was previously working fine. The problem arose after upgrading from node 16 to node 20. When attempting to run 'npm run dev', I started receiving the error message: Failed to resolve import ". ...

JavaScript's local storage feature seems to be failing in both saving and retrieving data

I'm working on a fun math game where two random numbers and a sign (+ or -) are generated using Math.random(). The user needs to input their answer in the provided input box. However, I am facing an issue with saving and retrieving the score and high ...

Creating an interactive Google line chart in MVC4

I am currently working on a dynamic line chart that needs to be able to adjust the number of lines (Standard, Latest, Earliest, Average) based on the database records. My code structure is similar to this example. function drawChart() { var data = ...

Trigger the React useEffect only when the inputed string matches the previous one

Currently, I am in the process of creating my own custom useFetch hook. export const useFetch = <T extends unknown>( url: string, options?: RequestInit ) => { const [loading, setLoading] = useState(false); const [error, setError] = ...

Can a web application be developed utilizing JavaScript to access the torch feature in Safari?

Currently working on a website that needs to utilize the flashlight feature on both android and IOS devices. Found a method to activate the torch from an android device using Chrome (link). However, this same code does not seem to be functional on my IOS d ...

Error Alert: Cannot access navigator in Angular Universal platform

I utilized the official angular-cli guide to incorporate angular-universal into my existing angular-cli application. Successfully implemented server-side rendering for my angular-cli app. However, upon attempting to integrate ngx-leaflet, I encountered th ...

What is the best way to implement bypassSecurityTrustResourceUrl for all elements within an array?

My challenge is dealing with an array of Google Map Embed API URLs. As I iterate over each item, I need to bind them to the source of an iFrame. I have a solution in mind: constructor(private sanitizer: DomSanitizationService) { this.url = sanitizer. ...