I’m trying to run an online study and I added a code component. I had to write some JavaScript code although I am not familiar with JavaScript
The following piece of code seems to be a problem:
l1 = listeb.slice();
l2 = sentencesfinal.slice();
let i = 0;
a = [];
b = [];
while (l1.length > 0) {
i = Math.floor(Math.random() * l1.length);
a.push(l1[i]);
l1.splice(i, 1);
b.push(l2[i]);
l2.splice(i, 1);
}
When piloting the experiment I get an error saying “TypeError: l1.splice is not a function”. However, the code itself seems to be fine and l1 is actually an array (and slice also works).
Hello JensBoelte,
thanks for your clarification question. I should have described what I want to achieve!
I have a two lists which I shuffle independently. Then I glue them together into a tuple (called c below), shuffle this tuple together and tease them apart to read them in.
#Finally, a tuple called "c" is created.
#This tuple brings the images and the sentences together
#The tuple then is randomly shuffled and then teased apart into
#two lists called "a" and "b"
c = list(zip(listeb,sentencesfinal))
shuffle(c)
a, b = zip(*c)
a=list(a)
b=list(b)
ok, sorry but why do you shuffle the two lists independently, glue them together, shuffle again, and split them? Wouldn’t you achieve the same result by simply shuffling the lists independently?
To shuffle lists in PsychoPy and PsychoJS, simply use the auto-translate functionality of the Builder, which translates PsychoPy to PsychoJS in a code-component set to Auto-JS.
python-side
shuffle(listA)
shuffle(listB)
This should give
util.shuffle(listA);
util.shuffle(listB);
on the JS-side. The most recent PsychoPy-version should autotranslate this properly. Otherwise add a JS-only component to a Begin-experiment tab and define
shuffle = util.shuffle;
splice extracts part of a string and returns the extracted part as a new string.
Thanks for your suggestion! Actually the code is much more complex with a lot of shuffeling involved before this particular line of code starts. But on the whole I often have the feeling that what I do is more complex than it could be I’ll try to solve my problem tonight. In any case I’m happy that there are active people in this forum
if you want to combine two lists, shuffle them, split them in two lists, you might want to use such code:
listA = [num for num in range(0,5)]
listB = ['a', 'b', 'c', 'd', 'e']
listAB = []
listAB = listA + listB
shuffle(listAB)
i = 0
while i < len(listA):
listA[i] = listAB[i]
listB[i] = listAB[i+5]
i += 1