Display List from Array Javascript | XM Community
Question

Display List from Array Javascript

  • 23 May 2023
  • 2 replies
  • 158 views

Badge +1

Hello! I am trying to create a study in which participants will be randomly shown 5 prewritten lists of items out of ~400 lists, and will be asked to rate each item in each list on a 7-point scale. Currently my code to display the lists looks like this: 

Qualtrics.SurveyEngine.addOnload(function() {

  // define an array of 400ish lists (5 shown as an example)

  const allCS = ["ex1", "ex2", "ex3", "ex4", "ex5"];

  

  // function to randomly select 5 lists from the array

  function selectRandomChoiceSets(array, count) {

    const shuffled = array.sort(() => 0.5 - Math.random());

    return shuffled.slice(0, count);

  }

  

  // randomly select 5 lists

  const selectedCS = selectRandomChoiceSets(allCS, 5);

  

  // display the lists within the question named ‘cs’

  const questionContainer = document.getElementById('cs');

  selectedCS.forEach(function(choiceSet, index) {

    const choiceSetElement = document.createElement('div');

    choiceSetElement.innerHTML = '<h3>Choice Set ' + (index + 1) + '</h3><ul><li>' + choiceSet + '</li></ul>';

    questionContainer.appendChild(choiceSetElement);

  });

});

 

I think I did something wrong with the display logic. Does anyone know how to get the lists to display?

Thank you!


2 replies

Userlevel 5
Badge +24

@jane1111 , 

Just a thought as I look at your code. The line const shuffled = array.sort(() => 0.5 - Math.random()); is used to shuffle the array randomly. However, the sort() function requires a comparison function to be passed as an argument. Modify the line to const shuffled = array.sort(() => Math.random() - 0.5); to see if that will properly shuffle the array?

 

Userlevel 7
Badge +33

Please correct me if I'm wrong. You have 400 predifined elements and out of which you want to pick randomly 5. I think you can use randomizer instead, you can create 400 embedded field for these elements and pick 5 out of 400. It's a system defined module and will always work.

Leave a Reply