psychopy.org | Reference | Downloads | Github

Python to JS translate, searching for objects in an array

Description of the problem:
" TypeError: Cannot use ‘in’ operator to search for ‘XXXXX’ in undefined"
I used the auto-translate function and am having a couple of issues.
My code is supposed to check if an object “selectedPrimeprac” can be found in an array “primeListprac”. If it is found in the list it is deleted.
The python code:
primeListprac = [“SOUL”, “PILE”, “WRECK”, “PLEAD”, “FLASH”, “TRIBE”, “EXTENT”, “COLONY”, “FUNERAL”, “MONARCH”]

if(selectedPrimeprac in primeListprac):
primeListprac.remove(selectedPrimeprac)

The JS code:
primeListprac = [“SPIRIT”, “STACK”, “CRASH”, “BEGGAR”, “BRIGHT”, “CHEIFTAN”, “DEGREE”, “SETTLE”, “ARCADE”, “MIGHTY”];

if (_pj.in_es6(selectedPrimeprac, primeListprac)) {
primeListprac.remove(selectedPrimeprac);
}

As far as I know, in javascript, operator in searches for the index, but not the string itself.
See here (bottom of the page)

Auto translate was working, my variable just wasn’t global here is the solution.

@Jasper_Wilson, just in case if you want an equivalent in JS:

if (primeListprac.indexOf(selectedPrimeprac) > -1) {
  // Get the index of the list item
  idx = primeListprac.indexOf(selectedPrimeprac);
  // remove item in place it using splice
  primeListprac.splice(idx, 1);
}

Alternatively, a one-liner, which only removes the item if it is found in the array

primeListprac.filter(item => item !== selectedPrimeprac)
1 Like