Add a for loop in array.map function

Twine Version: 2.92

Is it possible to smush a for loop in this so that it only prints the 1st 10 entries? Similar to below but it actually compiles :slight_smile:

    <<print $HiScoreChart.map(
    for (index <11){
    (who, index) => (index +1) + ". " + who.Name + ": " + who.Score +" points" ).join('<br>')
    }
    >>

I’m not at all familiar with Twine, but the code between <<print and >> looks like JavaScript. Is that right?

If so and if $HighScoreChart is an array, you can call .slice(0, 10) before the .map to just get the first 10 entries. There’s no way to stop looping from inside map (except throwing an exception, I guess).

If it’s not JavaScript, you’ll probably still need something like that - just with potentially different syntax.

Yes! That’s perfect. Thank you so much :slight_smile:

For anyone else wondering what methods can be used to achieve the desired outcome, some of them are…

1: Using the numerical index variant of the <<for>> macro.

<<nobr>>
	<<for _i to 0; _i < Math.min(10, $HiScoreChart.length); _i++>>
		<<if _i > 0>><br><</if>>
		<<= (_i +1) + ". " + $HiScoreChart[_i].Name + ": " + $HiScoreChart[_i].Score +" points">>
	<</for>>
<</nobr>>

note: this method relies on using the Math.min() method to control the upper bounds of the index.

2: Using the range variant of the same <<for>> macro.

<<nobr>>
	<<for _i, _who range $HiScoreChart.slice(0, 10)>>
		<<if _i > 0>><br><</if>>  
		<<= (_i +1) + ". " + _who.Name + ": " + _who.Score +" points">>
	<</for>>
<</nobr>>

note: this relies on the previously mentioned <array>.slice() method to create a temporary copy of the original array that has a maximum of 10 elements.

3: Using the <array>.map() method.

<<= $HiScoreChart.slice(0, 10).map( (who, index) => (index +1) + ". " + who.Name + ": " + who.Score + " points" ).join('<br>') >>
1 Like

Thats awesome. Thank you! I wasn’t aware of math.min and math.max. So useful!