Using js .findIndex to search array

Hi all, This is more of a javascript question.

I created an array of objects (named repeatLater) where each object consists of specifications of a that I’d want to repeat after a number of trials.

repeatLater.push({"word": word, "trlType": trlType, "trialN": trials.thisN, "exp_delay": delay, "minTrial": minTrial});

At the beginning of the routine, I am using findIndex to search through repeatLater to find the index of the first instance where the my specifications are met, in this case I want the trial number to be at least the minTrial. After retrieving the trial, I delete that object from the array.

repeatIdx = repeatLater.findIndex( x => x.minTrial <= trials.thisN );
delete repeatLater[repeatIdx];

Occasionally I get thrown this error : TypeError: Cannot read property ‘minTrial’ of undefined

I suspect that the problem might be because there are objects/entries in the repeatLater array that do not have the ‘minTrial’ key.

Looking at the console log it seems like the length of repeatLater is one plus the number of objects which is odd, the addition being proto.
Screenshot 2020-08-19 at 7.24.34 PM

Is there a way to for findIndex to ignore proto?

Thanks a lot,

The likely issue here is your use of delete:
tl;dr delete doesn’t reindex the array nor update its length (hence why you it appears you have four elements in the array but a length of 5) and the ‘rogue’ element, when looped through, will be undefined (causing the error you are encountering).
As the linked post suggested, you want to use splice instead. Replace
delete repeatLater[repeatIdx]
repeatLater.splice(repeatIdx, 1)

This should resolve the problem!

1 Like

Thank you @AJavascripter!
I would have took ages to notice the difference myself.