I need some help retrieving a combination of colors and numbers out of an array

If you are requesting technical assistance with Twine, please specify:
Twine Version: 2.3.13
Story Format: 2.34.1

After a lot of error messages and searching online I turn to you, hoping anyone can help me.

I am trying to get a variable integer based on some colors I picked. I might add some colors in the future.
But ensure the colors are different for each game, I want to assign each color a specific number at the start, in the storyInit.
So I did the following

I made some arrays and I fill the arrays with colors and numbers.
I could probably fill the numberlist with a for loop based on the colors.length now that I think of it.
I made a new variable, based on colors length so it will not mess up my for loop when I pluck items from it.

<<set $numbers = []>>
<<set $colors = []>>
<<set $numberlist = []>>

<<set $colors to ["red","black","blue","green","yellow","purple"]>>
<<set $numberlist to [0,1,2,3,4,5]>>

<<set $colorslength = $colors.length>>

<<for _i to 0; _i < $colorslength; _i++>>
	<<set $colors.push({
		colorcode: $colors.pluck(),
		result: $numberlist.pluck()

My idea is to have an array with a random combination of colors and numbers. This seems to work. But i can’t seem to find a way to input a color (for example blue) and retrieve the corresponding number.
I tried to make it work using indexOf:

given <<set $playerPick = "blue">>
<<set colornumber = "">> 

<<if 1 == 1>>
	<<set $colornumber = $colors.colorcode.indexOf($PlayerPick) >>

It will not surprise you this will not work and gives the following Error: <>: bad evaluation: Cannot read colorcode ‘indexOf’ of undefined

Should not use indexOf? is there another way to do what I want to achieve? I hope anyone can give me a pointer on where to look or what to do?

Any help would be greatly appreciated

Problem 1: Your loop is adding members to your original $colors array, which is unlikely what you want to be doing. I’d use temporary variables for the original colors and numberlist arrays, so you aren’t contaminating the final $colors array.

Problem 2: You cannot access the properties of an object within the array before you’ve found the object.

Try the following, using the <Array>.find() method:

<<set $colornumber = $colors.find(color => color.colorcode === $playerPick).colorcode>>

Though, ideally you’d check to ensure that you’d actually found a value before attempting to access its property. E.g.,

<<set _found = $colors.find(color => color.colorcode === $playerPick)>>
<<if def _found>>
    <<set $colornumber = _found.colorcode>>
1 Like